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

tensor_reformat.cpp 164 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579
  1. /**
  2. * \file src/gopt/impl/tensor_reformat.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
  10. * implied.
  11. */
  12. #include "megbrain/gopt/basic_arith.h"
  13. #include "megbrain/gopt/gtrans.h"
  14. #include "megbrain/gopt/inference.h"
  15. #include "megbrain/graph/event.h"
  16. #include "megbrain/opr/basic_arith.h"
  17. #include "megbrain/opr/blas.h"
  18. #include "megbrain/opr/dnn/batch_norm.h"
  19. #include "megbrain/opr/dnn/convolution.h"
  20. #include "megbrain/opr/dnn/local.h"
  21. #include "megbrain/opr/dnn/pooling.h"
  22. #include "megbrain/opr/imgproc.h"
  23. #include "megbrain/opr/misc.h"
  24. #include "megbrain/opr/nn_int.h"
  25. #include "megbrain/opr/tensor_manip.h"
  26. #include "megbrain/opr/utility.h"
  27. #include "megbrain/serialization/opr_shallow_copy.h"
  28. #include "megbrain/utils/shared_set.h"
  29. #include "megdnn/opr_param_defs.h"
  30. #include "megdnn/tensor_format.h"
  31. #include "megbrain/opr/internal/megdnn_opr_wrapper.h"
  32. #if MGB_ENABLE_TENSOR_RT
  33. #include "megbrain/tensorrt/tensorrt_opr.h"
  34. #endif
  35. #include "megbrain/gopt/misc.h"
  36. #include "megbrain/utils/hash_ct.h"
  37. #include "midout.h"
  38. MIDOUT_DECL(megbrain_tensor_reformat)
  39. #define MIDOUT_B(tag) \
  40. MIDOUT_BEGIN(megbrain_tensor_reformat, midout_iv(MGB_HASH_STR(tag))) {
  41. #define MIDOUT_E \
  42. } \
  43. MIDOUT_END();
  44. using namespace mgb;
  45. using namespace gopt;
  46. /* ================ TensorReformatPass =============== */
  47. /*!
  48. * \brief relayout placeholder opr
  49. *
  50. * RelayoutPlaceholder oprs act as the placeholders of the ComputingGraph
  51. * during graph opt pass `TensorReformatPass`. These oprs are introduced
  52. * into a ComputingGraph for conveniently discovering further optimize
  53. * opportunities (such as fuse consecutive relayouts, translate into
  54. * optimized implementations). They are canonized to have a shape infer, so
  55. * the ouput's shape can be correctly deduced during the opt pass.
  56. *
  57. * Note that the oprs in the ComputingGraph are only used as intermediate
  58. * representations before being translated to MegBrain oprs, so the
  59. * oprs should not get involved in any actual computing.
  60. */
  61. MGB_DEFINE_OPR_CLASS(TensorReformatPass::RelayoutPlaceholder,
  62. cg::SingleCNOperatorNodeBase) // {
  63. public:
  64. //! relayout type of this opr
  65. enum class LayoutType {
  66. NCHW4_TO_NCHW32, //!< from nchw4 layout to nchw32 layout
  67. NCHW32_TO_NCHW4, //!< from nchw32 layout to nchw4 layout
  68. NCHW4_TO_CHWN4, //!< from nchw4 layout to chwn4 layout
  69. CHWN4_TO_NCHW4, //!< from chwn4 layout to nchw4 layout
  70. NCHW_TO_NCHW4, //!< from nchw layout to nchw4 layout
  71. NCHW_TO_NCHW4_IC_SMALL_CONV, ///< from nchw layout to nchw4 whose
  72. ///< channel size less than 4
  73. NCHW4_TO_NCHW, //!< from nchw4 layout to nchw layout
  74. NCHW_TO_NCHW88, //!< from nchw layout to nchw88 layout
  75. NCHW88_TO_NCHW, //!< from nchw88 layout to nchw layout
  76. WEIGHT_NCHW_TO_NCHW4_DENSE, //!< weight from nchw layout to nchw4
  77. //!< layout
  78. WEIGHT_NCHW_TO_NCHW4_GROUP, //!< group weight from nchw layout to
  79. //!< nchw4 layout
  80. WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV, //!< weight from nchw layout
  81. //!< to nchw4 layout whose
  82. //! channel size less than 4
  83. WEIGHT_NCHW_TO_NCHW88_DENSE, //!< weight from nchw layout to nchw88
  84. //!< layout
  85. WEIGHT_NCHW_TO_NCHW88_GROUP, //!< group weight from nchw layout to
  86. //!< nchw88 layout
  87. WEIGHT_NCHW_TO_NCHW88_CHAN, //!< channel wise weight from nchw layout
  88. //!< to nchw88 layout
  89. //!< the weight layout of input is nchw output is nchw88, special for
  90. //!< shape weight in nchw like {64, 2, 3, 3} to {8, 3, 3, 2, 8}
  91. WEIGHT_HYBIRD_NCHW_NCHW88,
  92. WEIGHT_NCHW_TO_NCHW44_DENSE, //!< weight from nchw layout to nchw44
  93. //!< layout
  94. WEIGHT_NCHW_TO_NCHW44_GROUP, //!< group weight from nchw layout to
  95. //!< nchw44 layout
  96. WEIGHT_NCHW_TO_NCHW44_CHAN, //!< channel wise weight from nchw layout
  97. //!< to nchw44 layout
  98. //!< the weight layout of input is nchw output is nchw44, special for
  99. //!< shape weight in nchw like {64, 2, 3, 3} to {16, 3, 3, 2, 4}
  100. WEIGHT_HYBIRD_NCHW_NCHW44,
  101. WEIGHT_NCHW_TO_NCHW44_DOT_DENSE, //!< weight from NCHW44 layout to
  102. //!< NCHW44_DOT layout dense
  103. WEIGHT_NCHW_TO_NCHW44_DOT_GROUP, //!< weight from NCHW44 layout to
  104. //!< NCHW44_DOT layout group
  105. };
  106. RelayoutPlaceholder(VarNode* src_var, LayoutType layout_type);
  107. /*!
  108. * \param src_var the input var
  109. * \param layout_type tensor layout transform type of this relayout
  110. * placeholder as described in LayoutType
  111. */
  112. static SymbolVar make(VarNode* src_var, LayoutType layout_type);
  113. LayoutType layout_type() const {
  114. return m_layout_type;
  115. }
  116. private:
  117. void init_output_static_infer_desc() override;
  118. void scn_do_execute() override;
  119. void init_output_comp_node() override;
  120. const LayoutType m_layout_type;
  121. }
  122. ;
  123. MGB_DYN_TYPE_OBJ_FINAL_IMPL(TensorReformatPass::RelayoutPlaceholder);
  124. TensorReformatPass::RelayoutPlaceholder::RelayoutPlaceholder(
  125. VarNode* src_var, LayoutType layout_type)
  126. : Super(src_var->owner_graph(), {}, "RelayoutPlaceholder", {src_var}),
  127. m_layout_type{layout_type} {
  128. add_input({src_var});
  129. add_equivalence_component<ScalarHash<LayoutType>>(m_layout_type);
  130. add_output(None)->dtype(src_var->dtype());
  131. }
  132. void TensorReformatPass::RelayoutPlaceholder::scn_do_execute() {
  133. mgb_throw(InternalError, "RelayoutPlaceholder opr can not be executed");
  134. }
  135. void TensorReformatPass::RelayoutPlaceholder::init_output_comp_node() {
  136. output(0)->comp_node(input(0)->comp_node());
  137. }
  138. void TensorReformatPass::RelayoutPlaceholder::init_output_static_infer_desc() {
  139. using namespace cg::static_infer;
  140. auto&& mgr = owner_graph()->static_infer_manager();
  141. DepVal deps;
  142. for (auto i : input())
  143. deps.push_back({i, DepType::SHAPE});
  144. auto infer_shape = [this](TensorShape& dst, const InpVal& inp) {
  145. TensorShape inp_shape = inp.val[0].shape();
  146. dst = inp_shape;
  147. if (layout_type() == RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32) {
  148. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  149. dst[0] = inp_shape[0];
  150. dst[1] = inp_shape[1] / 8;
  151. dst[2] = inp_shape[2];
  152. dst[3] = inp_shape[3];
  153. dst[4] = inp_shape[4] * 8;
  154. } else if (layout_type() ==
  155. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4) {
  156. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
  157. dst[0] = inp_shape[0];
  158. dst[1] = inp_shape[1] * 8;
  159. dst[2] = inp_shape[2];
  160. dst[3] = inp_shape[3];
  161. dst[4] = inp_shape[4] / 8;
  162. } else if (layout_type() ==
  163. RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4) {
  164. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  165. dst[0] = inp_shape[1];
  166. dst[1] = inp_shape[2];
  167. dst[2] = inp_shape[3];
  168. dst[3] = inp_shape[0];
  169. dst[4] = inp_shape[4];
  170. } else if (layout_type() ==
  171. RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4) {
  172. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  173. dst[0] = inp_shape[3];
  174. dst[1] = inp_shape[0];
  175. dst[2] = inp_shape[1];
  176. dst[3] = inp_shape[2];
  177. dst[4] = inp_shape[4];
  178. } else if (layout_type() ==
  179. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4 ||
  180. layout_type() == RelayoutPlaceholder::LayoutType::
  181. NCHW_TO_NCHW4_IC_SMALL_CONV) {
  182. if (layout_type() ==
  183. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4) {
  184. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 4 == 0);
  185. } else {
  186. mgb_assert(layout_type() ==
  187. RelayoutPlaceholder::LayoutType::
  188. NCHW_TO_NCHW4_IC_SMALL_CONV);
  189. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] < 4);
  190. }
  191. dst.ndim = 5;
  192. dst[0] = inp_shape[0];
  193. dst[1] = (inp_shape[1] + 4 - 1) / 4;
  194. dst[2] = inp_shape[2];
  195. dst[3] = inp_shape[3];
  196. dst[4] = 4;
  197. } else if (layout_type() ==
  198. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW) {
  199. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  200. dst.ndim = 4;
  201. dst[0] = inp_shape[0];
  202. dst[1] = inp_shape[1] * 4;
  203. dst[2] = inp_shape[2];
  204. dst[3] = inp_shape[3];
  205. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  206. WEIGHT_NCHW_TO_NCHW4_DENSE ||
  207. layout_type() ==
  208. RelayoutPlaceholder::LayoutType::
  209. WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV) {
  210. if (layout_type() ==
  211. RelayoutPlaceholder::LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE) {
  212. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 4 == 0);
  213. } else {
  214. mgb_assert(layout_type() ==
  215. RelayoutPlaceholder::LayoutType::
  216. WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV);
  217. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] < 4);
  218. }
  219. dst.ndim = 5;
  220. dst[0] = inp_shape[0];
  221. dst[1] = (inp_shape[1] + 4 - 1) / 4;
  222. dst[2] = inp_shape[2];
  223. dst[3] = inp_shape[3];
  224. dst[4] = 4;
  225. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  226. WEIGHT_NCHW_TO_NCHW4_GROUP) {
  227. mgb_assert(inp_shape.ndim == 5 && inp_shape[2] % 4 == 0);
  228. dst.ndim = 6;
  229. dst[0] = inp_shape[0];
  230. dst[1] = inp_shape[1];
  231. dst[2] = inp_shape[2] / 4;
  232. dst[3] = inp_shape[3];
  233. dst[4] = inp_shape[4];
  234. dst[5] = 4;
  235. } else if (layout_type() ==
  236. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW88) {
  237. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 8 == 0);
  238. dst.ndim = 5;
  239. dst[0] = inp_shape[0];
  240. dst[1] = inp_shape[1] / 8;
  241. dst[2] = inp_shape[2];
  242. dst[3] = inp_shape[3];
  243. dst[4] = 8;
  244. } else if (layout_type() ==
  245. RelayoutPlaceholder::LayoutType::NCHW88_TO_NCHW) {
  246. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 8);
  247. dst.ndim = 4;
  248. dst[0] = inp_shape[0];
  249. dst[1] = inp_shape[1] * 8;
  250. dst[2] = inp_shape[2];
  251. dst[3] = inp_shape[3];
  252. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  253. WEIGHT_NCHW_TO_NCHW88_DENSE) {
  254. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 8 == 0 &&
  255. inp_shape[1] % 8 == 0);
  256. dst.ndim = 6;
  257. dst[0] = inp_shape[0] / 8;
  258. dst[1] = inp_shape[1] / 8;
  259. dst[2] = inp_shape[2];
  260. dst[3] = inp_shape[3];
  261. dst[4] = 8;
  262. dst[5] = 8;
  263. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  264. WEIGHT_NCHW_TO_NCHW88_GROUP) {
  265. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 8 == 0 &&
  266. inp_shape[2] % 8 == 0);
  267. dst.ndim = 7;
  268. dst[0] = inp_shape[0];
  269. dst[1] = inp_shape[1] / 8;
  270. dst[2] = inp_shape[2] / 8;
  271. dst[3] = inp_shape[3];
  272. dst[4] = inp_shape[4];
  273. dst[5] = 8;
  274. dst[6] = 8;
  275. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  276. WEIGHT_NCHW_TO_NCHW88_CHAN) {
  277. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] == 1 &&
  278. inp_shape[2] == 1 && inp_shape[0] % 8 == 0);
  279. dst.ndim = 6;
  280. dst[0] = inp_shape[0] / 8;
  281. dst[1] = inp_shape[1];
  282. dst[2] = inp_shape[2];
  283. dst[3] = inp_shape[3];
  284. dst[4] = inp_shape[4];
  285. dst[5] = 8;
  286. } else if (layout_type() ==
  287. RelayoutPlaceholder::LayoutType::WEIGHT_HYBIRD_NCHW_NCHW88) {
  288. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 8 == 0);
  289. dst.ndim = 5;
  290. dst[0] = inp_shape[0] / 8;
  291. dst[1] = inp_shape[2];
  292. dst[2] = inp_shape[3];
  293. dst[3] = inp_shape[1];
  294. dst[4] = 8;
  295. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  296. WEIGHT_NCHW_TO_NCHW44_DENSE ||
  297. layout_type() == RelayoutPlaceholder::LayoutType::
  298. WEIGHT_NCHW_TO_NCHW44_DOT_DENSE) {
  299. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 4 == 0 &&
  300. inp_shape[1] % 4 == 0);
  301. dst.ndim = 6;
  302. dst[0] = inp_shape[0] / 4;
  303. dst[1] = inp_shape[1] / 4;
  304. dst[2] = inp_shape[2];
  305. dst[3] = inp_shape[3];
  306. dst[4] = 4;
  307. dst[5] = 4;
  308. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  309. WEIGHT_NCHW_TO_NCHW44_GROUP ||
  310. layout_type() == RelayoutPlaceholder::LayoutType::
  311. WEIGHT_NCHW_TO_NCHW44_DOT_GROUP) {
  312. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 4 == 0 &&
  313. inp_shape[2] % 4 == 0);
  314. dst.ndim = 7;
  315. dst[0] = inp_shape[0];
  316. dst[1] = inp_shape[1] / 4;
  317. dst[2] = inp_shape[2] / 4;
  318. dst[3] = inp_shape[3];
  319. dst[4] = inp_shape[4];
  320. dst[5] = 4;
  321. dst[6] = 4;
  322. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  323. WEIGHT_NCHW_TO_NCHW44_CHAN) {
  324. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] == 1 &&
  325. inp_shape[2] == 1 && inp_shape[0] % 4 == 0);
  326. dst.ndim = 6;
  327. dst[0] = inp_shape[0] / 4;
  328. dst[1] = inp_shape[1];
  329. dst[2] = inp_shape[2];
  330. dst[3] = inp_shape[3];
  331. dst[4] = inp_shape[4];
  332. dst[5] = 4;
  333. } else {
  334. mgb_assert(
  335. layout_type() ==
  336. RelayoutPlaceholder::LayoutType::WEIGHT_HYBIRD_NCHW_NCHW44);
  337. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 4 == 0);
  338. dst.ndim = 5;
  339. dst[0] = inp_shape[0] / 4;
  340. dst[1] = inp_shape[2];
  341. dst[2] = inp_shape[3];
  342. dst[3] = inp_shape[1];
  343. dst[4] = 4;
  344. }
  345. return true;
  346. };
  347. mgr.register_shape_infer(output(0), {SourceType::DEP, deps, infer_shape});
  348. }
  349. SymbolVar TensorReformatPass::RelayoutPlaceholder::make(
  350. VarNode* src_var, LayoutType layout_type) {
  351. return src_var->owner_graph()
  352. ->insert_opr(
  353. std::make_unique<RelayoutPlaceholder>(src_var, layout_type))
  354. ->output(0);
  355. }
  356. void TensorReformatPass::insert_pass(OptState& opt) const {
  357. opt.set_var_replace_check_flag(m_var_replace_check_flag);
  358. auto rewriter = opt.graph().make_rewriter();
  359. VarNodeArray new_inp_cache;
  360. auto on_opr = [this, &opt, &rewriter,
  361. &new_inp_cache](OperatorNodeBase* opr) {
  362. auto it = m_opr_replace_func.find(opr->dyn_typeinfo());
  363. if (it != m_opr_replace_func.end()) {
  364. auto& new_inp = new_inp_cache;
  365. new_inp.clear();
  366. new_inp.reserve(opr->input().size());
  367. for (auto&& inp : opr->input()) {
  368. new_inp.push_back(rewriter.get_var(inp));
  369. }
  370. auto new_opr = (it->second)(opr, new_inp);
  371. auto &&out0 = opr->output(), &&out1 = new_opr->output();
  372. mgb_assert(out0.size() == out1.size(),
  373. "bad opr replace: src=%s{%s} dst=%s{%s}, "
  374. "src.size=%zu "
  375. "dst.size=%zu",
  376. opr->cname(), opr->dyn_typeinfo()->name,
  377. new_opr->cname(), new_opr->dyn_typeinfo()->name,
  378. out0.size(), out1.size());
  379. for (size_t i = 0; i < out0.size(); ++i) {
  380. if (!out0[i]->contain_flag(VarNode::Flag::VOLATILE_CONTENT)) {
  381. mgb_assert(!out1[i]->contain_flag(
  382. VarNode::Flag::VOLATILE_CONTENT));
  383. auto src = out0[i];
  384. auto dst = out1[i];
  385. if (opt.graph().endpoint_contain(src)) {
  386. // additional process on endpoint var node
  387. dst = on_graph_endpoint_var(dst, src);
  388. }
  389. rewriter.replace_var(src, dst, nullptr);
  390. }
  391. }
  392. } else {
  393. rewriter.auto_replace_outputs(opr);
  394. }
  395. };
  396. opt.graph().iter(on_opr);
  397. rewriter.apply_inplace();
  398. }
  399. void TensorReformatPass::translate_pass(OptState& opt) const {
  400. ThinHashMap<RelayoutPlaceholder::LayoutType,
  401. thin_function<VarNode*(VarNode*)>>
  402. reformat;
  403. using LayoutType = RelayoutPlaceholder::LayoutType;
  404. reformat[LayoutType::NCHW4_TO_CHWN4] = [](VarNode* inp) -> VarNode* {
  405. megdnn::param::RelayoutFormat param;
  406. param.mode = megdnn::param::RelayoutFormat::Mode::NCHW4_CHWN4;
  407. auto reformat = opr::RelayoutFormat::make(inp, param);
  408. return reformat.node();
  409. };
  410. reformat[LayoutType::CHWN4_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
  411. megdnn::param::RelayoutFormat param;
  412. param.mode = megdnn::param::RelayoutFormat::Mode::CHWN4_NCHW4;
  413. auto reformat = opr::RelayoutFormat::make(inp, param);
  414. return reformat.node();
  415. };
  416. reformat[LayoutType::NCHW4_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
  417. auto x = SymbolVar(inp);
  418. auto xshp = opr::GetVarShape::make(x);
  419. auto cv = [&x](int v) { return x.make_scalar(v); };
  420. auto sub = [&xshp, &cv](int idx) {
  421. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  422. };
  423. auto tshp0 = opr::Concat::make(
  424. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)}, 0),
  425. tshp1 = opr::Concat::make(
  426. {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
  427. auto y0 = opr::Reshape::make(x, tshp0);
  428. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  429. auto y2 = opr::Reshape::make(y1, tshp1);
  430. return y2.node();
  431. };
  432. reformat[LayoutType::NCHW32_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
  433. auto x = SymbolVar(inp);
  434. auto xshp = opr::GetVarShape::make(x);
  435. auto cv = [&x](int v) { return x.make_scalar(v); };
  436. auto sub = [&xshp, &cv](int idx) {
  437. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  438. };
  439. auto tshp0 = opr::Concat::make(
  440. {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8}, 0),
  441. tshp1 = opr::Concat::make(
  442. {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
  443. auto y0 = opr::Reshape::make(x, tshp0);
  444. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  445. auto y2 = opr::Reshape::make(y1, tshp1);
  446. return y2.node();
  447. };
  448. reformat[LayoutType::NCHW_TO_NCHW4_IC_SMALL_CONV] =
  449. [](VarNode* inp) -> VarNode* {
  450. auto x = SymbolVar(inp);
  451. auto y = opr::RelayoutFormat::make(
  452. x, megdnn::param::RelayoutFormat::Mode::NCHW_NCHW4_IC_SMALL);
  453. return y.node();
  454. };
  455. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV] =
  456. [](VarNode* inp) -> VarNode* {
  457. auto x = SymbolVar(inp);
  458. auto y = opr::RelayoutFormat::make(
  459. x, megdnn::param::RelayoutFormat::Mode::
  460. NCHW_NCHW4_IC_SMALL_CONV_DENSE_WEIGHT);
  461. return y.node();
  462. };
  463. reformat[LayoutType::NCHW_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
  464. auto x = SymbolVar(inp);
  465. auto xshp = opr::GetVarShape::make(x);
  466. auto cv = [&x](int v) { return x.make_scalar(v); };
  467. auto sub = [&xshp, &cv](int idx) {
  468. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  469. };
  470. auto tshp0 = opr::Concat::make(
  471. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
  472. auto y0 = opr::Reshape::make(x, tshp0);
  473. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  474. return y1.node();
  475. };
  476. reformat[LayoutType::NCHW4_TO_NCHW] = [](VarNode* inp) -> VarNode* {
  477. auto x = SymbolVar(inp);
  478. auto xshp = opr::GetVarShape::make(x);
  479. auto cv = [&x](int v) { return x.make_scalar(v); };
  480. auto sub = [&xshp, &cv](int idx) {
  481. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  482. };
  483. auto tshp0 = opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
  484. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  485. auto y1 = opr::Reshape::make(y0, tshp0);
  486. return y1.node();
  487. };
  488. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE] =
  489. [](VarNode* inp) -> VarNode* {
  490. auto x = SymbolVar(inp);
  491. auto xshp = opr::GetVarShape::make(x);
  492. auto cv = [&x](int v) { return x.make_scalar(v); };
  493. auto sub = [&xshp, &cv](int idx) {
  494. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  495. };
  496. auto tshp0 = opr::Concat::make(
  497. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
  498. tshp1 = opr::Concat::make(
  499. {sub(0), sub(1) / 4, sub(2), sub(3), cv(4)}, 0);
  500. auto y0 = opr::Reshape::make(x, tshp0);
  501. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  502. auto y2 = opr::Reshape::make(y1, tshp1);
  503. return y2.node();
  504. };
  505. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_GROUP] =
  506. [](VarNode* inp) -> VarNode* {
  507. auto x = SymbolVar(inp);
  508. auto xshp = opr::GetVarShape::make(x);
  509. auto cv = [&x](int v) { return x.make_scalar(v); };
  510. auto sub = [&xshp, &cv](int idx) {
  511. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  512. };
  513. auto tshp0 = opr::Concat::make(
  514. {sub(0), sub(1), sub(2) / 4, cv(4), sub(3), sub(4)}, 0),
  515. tshp1 = opr::Concat::make(
  516. {sub(0), sub(1), sub(2) / 4, sub(3), sub(4), cv(4)}, 0);
  517. auto y0 = opr::Reshape::make(x, tshp0);
  518. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 2, 4, 5, 3});
  519. auto y2 = opr::Reshape::make(y1, tshp1);
  520. return y2.node();
  521. };
  522. reformat[LayoutType::NCHW_TO_NCHW88] = [](VarNode* inp) -> VarNode* {
  523. auto x = SymbolVar(inp);
  524. auto xshp = opr::GetVarShape::make(x);
  525. auto cv = [&x](int v) { return x.make_scalar(v); };
  526. auto sub = [&xshp, &cv](int idx) {
  527. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  528. };
  529. auto tshp0 = opr::Concat::make(
  530. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3)}, 0),
  531. tshp1 = opr::Concat::make(
  532. {sub(0), sub(1) / 8, sub(2), sub(3), cv(8)}, 0);
  533. auto y0 = opr::Reshape::make(x, tshp0);
  534. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  535. auto y2 = opr::Reshape::make(y1, tshp1);
  536. return y2.node();
  537. };
  538. reformat[LayoutType::NCHW88_TO_NCHW] = [](VarNode* inp) -> VarNode* {
  539. auto x = SymbolVar(inp);
  540. auto xshp = opr::GetVarShape::make(x);
  541. auto cv = [&x](int v) { return x.make_scalar(v); };
  542. auto sub = [&xshp, &cv](int idx) {
  543. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  544. };
  545. auto tshp0 = opr::Concat::make({sub(0), sub(1) * 8, sub(2), sub(3)}, 0);
  546. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  547. auto y1 = opr::Reshape::make(y0, tshp0);
  548. return y1.node();
  549. };
  550. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_DENSE] =
  551. [](VarNode* inp) -> VarNode* {
  552. auto x = SymbolVar(inp);
  553. auto xshp = opr::GetVarShape::make(x);
  554. auto cv = [&x](int v) { return x.make_scalar(v); };
  555. auto sub = [&xshp, &cv](int idx) {
  556. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  557. };
  558. auto tshp0 = opr::Concat::make(
  559. {sub(0) / 8, cv(8), sub(1) / 8, cv(8), sub(2), sub(3)}, 0),
  560. tshp1 = opr::Concat::make(
  561. {sub(0) / 8, sub(1) / 8, sub(2), sub(3), cv(8), cv(8)}, 0);
  562. auto y0 = opr::Reshape::make(x, tshp0);
  563. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 3, 1});
  564. auto y2 = opr::Reshape::make(y1, tshp1);
  565. return y2.node();
  566. };
  567. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_GROUP] =
  568. [](VarNode* inp) -> VarNode* {
  569. auto x = SymbolVar(inp);
  570. auto xshp = opr::GetVarShape::make(x);
  571. auto cv = [&x](int v) { return x.make_scalar(v); };
  572. auto sub = [&xshp, &cv](int idx) {
  573. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  574. };
  575. auto tshp0 = opr::Concat::make({sub(0), sub(1) / 8, cv(8), sub(2) / 8,
  576. cv(8), sub(3), sub(4)},
  577. 0),
  578. tshp1 = opr::Concat::make({sub(0), sub(1) / 8, sub(2) / 8, sub(3),
  579. sub(4), cv(8), cv(8)},
  580. 0);
  581. auto y0 = opr::Reshape::make(x, tshp0);
  582. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 4, 2});
  583. auto y2 = opr::Reshape::make(y1, tshp1);
  584. return y2.node();
  585. };
  586. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_CHAN] =
  587. [](VarNode* inp) -> VarNode* {
  588. auto x = SymbolVar(inp);
  589. auto xshp = opr::GetVarShape::make(x);
  590. auto cv = [&x](int v) { return x.make_scalar(v); };
  591. auto sub = [&xshp, &cv](int idx) {
  592. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  593. };
  594. auto tshp0 = opr::Concat::make(
  595. {sub(0) / 8, cv(8), sub(1), sub(2), sub(3), sub(4)}, 0),
  596. tshp1 = opr::Concat::make(
  597. {sub(0) / 8, sub(1), sub(2), sub(3), sub(4), cv(8)}, 0);
  598. auto y0 = opr::Reshape::make(x, tshp0);
  599. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 3, 4, 5, 1});
  600. auto y2 = opr::Reshape::make(y1, tshp1);
  601. return y2.node();
  602. };
  603. reformat[LayoutType::WEIGHT_HYBIRD_NCHW_NCHW88] =
  604. [](VarNode* inp) -> VarNode* {
  605. auto x = SymbolVar(inp);
  606. auto xshp = opr::GetVarShape::make(x);
  607. auto cv = [&x](int v) { return x.make_scalar(v); };
  608. auto sub = [&xshp, &cv](int idx) {
  609. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  610. };
  611. auto tshp0 = opr::Concat::make(
  612. {sub(0) / 8, cv(8), sub(1), sub(2), sub(3)}, 0),
  613. tshp1 = opr::Concat::make(
  614. {sub(0) / 8, sub(2), sub(3), sub(1), cv(8)}, 0);
  615. auto y0 = opr::Reshape::make(x, tshp0);
  616. auto y1 = opr::Dimshuffle::make(y0, {0, 3, 4, 2, 1});
  617. auto y2 = opr::Reshape::make(y1, tshp1);
  618. return y2.node();
  619. };
  620. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DENSE] =
  621. [](VarNode* inp) -> VarNode* {
  622. auto x = SymbolVar(inp);
  623. auto xshp = opr::GetVarShape::make(x);
  624. auto cv = [&x](int v) { return x.make_scalar(v); };
  625. auto sub = [&xshp, &cv](int idx) {
  626. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  627. };
  628. auto tshp0 = opr::Concat::make(
  629. {sub(0) / 4, cv(4), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
  630. tshp1 = opr::Concat::make(
  631. {sub(0) / 4, sub(1) / 4, sub(2), sub(3), cv(4), cv(4)}, 0);
  632. auto y0 = opr::Reshape::make(x, tshp0);
  633. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 3, 1});
  634. auto y2 = opr::Reshape::make(y1, tshp1);
  635. return y2.node();
  636. };
  637. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_GROUP] =
  638. [](VarNode* inp) -> VarNode* {
  639. auto x = SymbolVar(inp);
  640. auto xshp = opr::GetVarShape::make(x);
  641. auto cv = [&x](int v) { return x.make_scalar(v); };
  642. auto sub = [&xshp, &cv](int idx) {
  643. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  644. };
  645. auto tshp0 = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2) / 4,
  646. cv(4), sub(3), sub(4)},
  647. 0),
  648. tshp1 = opr::Concat::make({sub(0), sub(1) / 4, sub(2) / 4, sub(3),
  649. sub(4), cv(4), cv(4)},
  650. 0);
  651. auto y0 = opr::Reshape::make(x, tshp0);
  652. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 4, 2});
  653. auto y2 = opr::Reshape::make(y1, tshp1);
  654. return y2.node();
  655. };
  656. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_CHAN] =
  657. [](VarNode* inp) -> VarNode* {
  658. auto x = SymbolVar(inp);
  659. auto xshp = opr::GetVarShape::make(x);
  660. auto cv = [&x](int v) { return x.make_scalar(v); };
  661. auto sub = [&xshp, &cv](int idx) {
  662. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  663. };
  664. auto tshp0 = opr::Concat::make(
  665. {sub(0) / 4, cv(4), sub(1), sub(2), sub(3), sub(4)}, 0),
  666. tshp1 = opr::Concat::make(
  667. {sub(0) / 4, sub(1), sub(2), sub(3), sub(4), cv(4)}, 0);
  668. auto y0 = opr::Reshape::make(x, tshp0);
  669. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 3, 4, 5, 1});
  670. auto y2 = opr::Reshape::make(y1, tshp1);
  671. return y2.node();
  672. };
  673. reformat[LayoutType::WEIGHT_HYBIRD_NCHW_NCHW44] =
  674. [](VarNode* inp) -> VarNode* {
  675. auto x = SymbolVar(inp);
  676. auto xshp = opr::GetVarShape::make(x);
  677. auto cv = [&x](int v) { return x.make_scalar(v); };
  678. auto sub = [&xshp, &cv](int idx) {
  679. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  680. };
  681. auto tshp0 = opr::Concat::make(
  682. {sub(0) / 4, cv(4), sub(1), sub(2), sub(3)}, 0),
  683. tshp1 = opr::Concat::make(
  684. {sub(0) / 4, sub(2), sub(3), sub(1), cv(4)}, 0);
  685. auto y0 = opr::Reshape::make(x, tshp0);
  686. auto y1 = opr::Dimshuffle::make(y0, {0, 3, 4, 2, 1});
  687. auto y2 = opr::Reshape::make(y1, tshp1);
  688. return y2.node();
  689. };
  690. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DOT_DENSE] =
  691. [](VarNode* inp) -> VarNode* {
  692. auto x = SymbolVar(inp);
  693. auto xshp = opr::GetVarShape::make(x);
  694. auto cv = [&x](int v) { return x.make_scalar(v); };
  695. auto sub = [&xshp, &cv](int idx) {
  696. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  697. };
  698. auto tshp0 = opr::Concat::make(
  699. {sub(0) / 4, cv(4), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
  700. tshp1 = opr::Concat::make(
  701. {sub(0) / 4, sub(1) / 4, sub(2), sub(3), cv(4), cv(4)}, 0);
  702. auto y0 = opr::Reshape::make(x, tshp0);
  703. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 1, 3});
  704. auto y2 = opr::Reshape::make(y1, tshp1);
  705. return y2.node();
  706. };
  707. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DOT_GROUP] =
  708. [](VarNode* inp) -> VarNode* {
  709. auto x = SymbolVar(inp);
  710. auto xshp = opr::GetVarShape::make(x);
  711. auto cv = [&x](int v) { return x.make_scalar(v); };
  712. auto sub = [&xshp, &cv](int idx) {
  713. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  714. };
  715. auto tshp0 = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2) / 4,
  716. cv(4), sub(3), sub(4)},
  717. 0),
  718. tshp1 = opr::Concat::make({sub(0), sub(1) / 4, sub(2) / 4, sub(3),
  719. sub(4), cv(4), cv(4)},
  720. 0);
  721. auto y0 = opr::Reshape::make(x, tshp0);
  722. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 2, 4});
  723. auto y2 = opr::Reshape::make(y1, tshp1);
  724. return y2.node();
  725. };
  726. auto rewriter = opt.graph().make_rewriter();
  727. auto on_opr = [&reformat, &rewriter](OperatorNodeBase* opr) {
  728. if (opr->same_type<RelayoutPlaceholder>()) {
  729. auto ph = try_cast_as_op<RelayoutPlaceholder>(opr);
  730. auto new_inp = rewriter.get_var(opr->input(0));
  731. mgb_assert(reformat.count(ph->layout_type()),
  732. "no replace rule can be found for layout_type(%u)",
  733. static_cast<uint32_t>(ph->layout_type()));
  734. auto new_var = reformat[ph->layout_type()](new_inp);
  735. rewriter.replace_var(opr->output(0), new_var,
  736. mgb_cstr_log("replace relayout placeholder"));
  737. return;
  738. }
  739. rewriter.auto_replace_outputs(opr);
  740. };
  741. opt.graph().iter(on_opr);
  742. rewriter.apply_inplace();
  743. }
  744. void TensorReformatPass::apply(OptState& opt) const {
  745. MIDOUT_B("TensorReformatPass::apply")
  746. insert_pass(opt);
  747. translate_pass(opt);
  748. MIDOUT_E
  749. }
  750. /* ================ EnableTensorCorePass =============== */
  751. VarNode* EnableTensorCorePass::on_graph_endpoint_var(VarNode* new_var,
  752. VarNode* orig_var) const {
  753. if (!orig_var->shape().eq_shape(new_var->shape())) {
  754. return RelayoutPlaceholder::make(
  755. new_var,
  756. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4)
  757. .node();
  758. }
  759. return new_var;
  760. }
  761. std::unique_ptr<EnableTensorCorePass>
  762. EnableTensorCorePass::make_tensorcore_converter() {
  763. MIDOUT_B("EnableTensorCorePass::make")
  764. // replace rule for conv bias opr
  765. auto replace_conv_bias_opr = [](OperatorNodeBase* opr,
  766. const VarNodeArray& new_inp) {
  767. using Param = megdnn::param::ConvBias;
  768. using Format = Param::Format;
  769. using Sparse = Param::Sparse;
  770. mgb_assert(opr->input().size() == new_inp.size());
  771. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  772. if (conv_bias.param().format != Format::NCHW4 ||
  773. conv_bias.output(0)->dtype().enumv() != DTypeEnum::QuantizedS8) {
  774. size_t nr_inps = opr->input().size();
  775. bool shape_has_changed = false;
  776. for (size_t i = 0; i < nr_inps; ++i) {
  777. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  778. shape_has_changed = true;
  779. }
  780. }
  781. MGB_MARK_USED_VAR(shape_has_changed);
  782. mgb_assert(
  783. !shape_has_changed,
  784. "EnableTensorCorePass assumes that the shape of inputs of"
  785. "ConvBias operators whose output dtype is not QuantizedS8 "
  786. "can not be changed in this opt pass");
  787. return serialization::copy_opr_shallow(*opr, new_inp,
  788. opr->config());
  789. }
  790. mgb_assert(opr->input(1)->shape().eq_shape(new_inp[1]->shape()),
  791. "EnableTensorCorePass assumes that filter tensor of "
  792. "conv_bias operator can not be changed by other operators");
  793. VarNode* orig_filter = opr->input(1);
  794. auto is_nchw4 = [](TensorShape shape) -> bool {
  795. return shape.ndim == 5 && shape[4] == 4;
  796. };
  797. auto is_nchw32 = [](TensorShape shape) -> bool {
  798. return shape.ndim == 5 && shape[4] == 32;
  799. };
  800. bool can_replace_nchw32 = false;
  801. VarNode *src = nullptr, *weight = nullptr, *bias = nullptr,
  802. *z_inp = nullptr;
  803. // process src tensor
  804. if (is_nchw4(new_inp[0]->shape())) { // new input is NCHW4 layout
  805. size_t group = 1, icpg, ocpg;
  806. if (conv_bias.param().sparse == Sparse::DENSE) {
  807. icpg = orig_filter->shape()[1] * 4;
  808. ocpg = orig_filter->shape()[0];
  809. } else {
  810. mgb_assert(conv_bias.param().sparse == Sparse::GROUP);
  811. group = orig_filter->shape()[0];
  812. icpg = orig_filter->shape()[2];
  813. ocpg = orig_filter->shape()[1];
  814. if (icpg == 1 && ocpg == 1) { // channel wise conv
  815. group *= 4;
  816. } else {
  817. icpg *= 4;
  818. }
  819. }
  820. // nchw32 layout need that input width and height are larger than 3
  821. size_t ih = new_inp[0]->shape()[2], iw = new_inp[0]->shape()[3];
  822. if (group == 1 && ocpg % 32 == 0 && icpg % 32 == 0 && ih >= 3 &&
  823. iw >= 3) {
  824. auto symvar = RelayoutPlaceholder::make(
  825. new_inp[0],
  826. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
  827. src = symvar.node();
  828. can_replace_nchw32 = true;
  829. } else {
  830. src = new_inp[0];
  831. }
  832. } else { // new input is NCHW32 layout
  833. mgb_assert(is_nchw32(new_inp[0]->shape()));
  834. size_t group = 1, ocpg;
  835. if (conv_bias.param().sparse == Sparse::DENSE) {
  836. ocpg = orig_filter->shape()[0];
  837. } else {
  838. mgb_assert(conv_bias.param().sparse == Sparse::GROUP);
  839. size_t icpg = orig_filter->shape()[2];
  840. ocpg = orig_filter->shape()[1];
  841. if (icpg == 1 && ocpg == 1) {
  842. group *= 4;
  843. } else {
  844. icpg *= 4;
  845. }
  846. }
  847. size_t ih = new_inp[0]->shape()[2], iw = new_inp[0]->shape()[3];
  848. if (group == 1 && ocpg % 32 == 0 && ih >= 3 && iw >= 3) {
  849. can_replace_nchw32 = true;
  850. src = new_inp[0];
  851. } else {
  852. auto symvar = RelayoutPlaceholder::make(
  853. new_inp[0],
  854. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
  855. src = symvar.node();
  856. }
  857. }
  858. // process filter tensor
  859. if (can_replace_nchw32) {
  860. auto symvar = RelayoutPlaceholder::make(
  861. new_inp[1],
  862. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
  863. weight = symvar.node();
  864. } else {
  865. weight = new_inp[1];
  866. }
  867. if (new_inp.size() == 2) {
  868. if (can_replace_nchw32) {
  869. auto param = conv_bias.param();
  870. param.format = Format::NCHW32;
  871. auto new_opr = opr::ConvBiasForward::make(
  872. src, weight, param, conv_bias.execution_policy(),
  873. conv_bias.config());
  874. return new_opr.node()->owner_opr();
  875. } else {
  876. VarNodeArray inps{src, weight};
  877. auto new_opr = serialization::copy_opr_shallow(*opr, inps,
  878. opr->config());
  879. return new_opr;
  880. }
  881. }
  882. auto process_inp = [&](VarNode* inp) -> VarNode* {
  883. if (can_replace_nchw32) {
  884. if (is_nchw4(inp->shape())) {
  885. auto symvar = RelayoutPlaceholder::make(
  886. inp,
  887. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
  888. return symvar.node();
  889. } else {
  890. mgb_assert(is_nchw32(inp->shape()));
  891. return inp;
  892. }
  893. } else {
  894. if (is_nchw4(inp->shape())) {
  895. return inp;
  896. } else {
  897. mgb_assert(is_nchw32(inp->shape()));
  898. auto symvar = RelayoutPlaceholder::make(
  899. inp,
  900. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
  901. return symvar.node();
  902. }
  903. }
  904. };
  905. // process bias tensor
  906. bias = process_inp(new_inp[2]);
  907. if (new_inp.size() == 3) {
  908. if (can_replace_nchw32) {
  909. auto param = conv_bias.param();
  910. param.format = Format::NCHW32;
  911. auto new_opr = opr::ConvBiasForward::make(
  912. src, weight, bias, param, conv_bias.execution_policy(),
  913. conv_bias.config());
  914. return new_opr.node()->owner_opr();
  915. } else {
  916. VarNodeArray inps{src, weight, bias};
  917. auto new_opr = serialization::copy_opr_shallow(*opr, inps,
  918. opr->config());
  919. return new_opr;
  920. }
  921. }
  922. // process z_inp tensor
  923. z_inp = process_inp(new_inp[3]);
  924. if (can_replace_nchw32) {
  925. auto param = conv_bias.param();
  926. param.format = Format::NCHW32;
  927. auto new_opr = opr::ConvBiasForward::make(
  928. src, weight, bias, z_inp, param,
  929. conv_bias.execution_policy(), conv_bias.config());
  930. return new_opr.node()->owner_opr();
  931. }
  932. VarNodeArray inps{src, weight, bias, z_inp};
  933. auto new_opr =
  934. serialization::copy_opr_shallow(*opr, inps, opr->config());
  935. return new_opr;
  936. };
  937. // replace rule for elemwise like opr
  938. // for oprs support NCHW4 and NCHW32 layout
  939. auto replace_elemwise_like_opr = [](OperatorNodeBase* opr,
  940. const VarNodeArray new_inp) {
  941. mgb_assert(opr->input().size() == new_inp.size());
  942. size_t nr_inps = new_inp.size();
  943. size_t nr_shape_changed = 0;
  944. for (size_t i = 0; i < nr_inps; ++i) {
  945. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  946. nr_shape_changed++;
  947. }
  948. }
  949. if (nr_shape_changed) {
  950. auto inps = new_inp;
  951. if (nr_shape_changed >=
  952. nr_inps / 2) { // NCHW32 > NCHW4 -> use NCHW32
  953. for (size_t i = 0; i < nr_inps; ++i) {
  954. if (opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  955. auto symvar = RelayoutPlaceholder::make(
  956. new_inp[i], RelayoutPlaceholder::LayoutType::
  957. NCHW4_TO_NCHW32);
  958. inps[i] = symvar.node();
  959. }
  960. }
  961. } else { // NCHW32 < NCHW4 -> use NCHW4
  962. for (size_t i = 0; i < nr_inps; ++i) {
  963. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  964. auto symvar = RelayoutPlaceholder::make(
  965. new_inp[i], RelayoutPlaceholder::LayoutType::
  966. NCHW32_TO_NCHW4);
  967. inps[i] = symvar.node();
  968. }
  969. }
  970. }
  971. return serialization::copy_opr_shallow(*opr, inps, opr->config());
  972. }
  973. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  974. };
  975. // for oprs only supports NCHW4 layout
  976. auto replace_inps_to_nchw4 = [](OperatorNodeBase* opr,
  977. const VarNodeArray new_inp) {
  978. mgb_assert(opr->input().size() == new_inp.size());
  979. VarNodeArray inps = new_inp;
  980. for (size_t i = 0; i < opr->input().size(); ++i) {
  981. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  982. mgb_assert(opr->input(i)->shape().ndim == 5 &&
  983. opr->input(i)->shape()[4] == 4);
  984. mgb_assert(new_inp[i]->shape().ndim == 5 &&
  985. new_inp[i]->shape()[4] == 32);
  986. auto symvar = RelayoutPlaceholder::make(
  987. new_inp[i],
  988. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
  989. inps[i] = symvar.node();
  990. }
  991. }
  992. auto new_opr =
  993. serialization::copy_opr_shallow(*opr, inps, opr->config());
  994. return new_opr;
  995. };
  996. auto replace_non_nchw4_opr = [](OperatorNodeBase* opr,
  997. const VarNodeArray new_inp) {
  998. size_t nr_inps = opr->input().size();
  999. bool shape_has_changed = false;
  1000. for (size_t i = 0; i < nr_inps; ++i) {
  1001. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1002. shape_has_changed = true;
  1003. }
  1004. }
  1005. mgb_assert(!shape_has_changed,
  1006. "EnableTensorCorePass assumes that inputs' shape of "
  1007. "non-nchw4 operators "
  1008. "can not be changed in this opt "
  1009. "pass");
  1010. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1011. };
  1012. auto replace_warp_affine_opr =
  1013. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1014. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1015. using Param = opr::WarpAffineForward::Param;
  1016. using Format = Param::Format;
  1017. mgb_assert(opr->input().size() == new_inp.size());
  1018. auto& warp = opr->cast_final_safe<opr::WarpAffineForward>();
  1019. if (warp.param().format != Format::NCHW4) {
  1020. return replace_non_nchw4_opr(opr, new_inp);
  1021. }
  1022. return replace_inps_to_nchw4(opr, new_inp);
  1023. };
  1024. auto replace_warp_perspective_opr =
  1025. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1026. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1027. using Param = opr::WarpPerspectiveForward::Param;
  1028. using Format = Param::Format;
  1029. mgb_assert(opr->input().size() == new_inp.size());
  1030. auto& warp =
  1031. opr->cast_final_safe<opr::WarpPerspectiveForward>();
  1032. if (warp.param().format != Format::NCHW4) {
  1033. return replace_non_nchw4_opr(opr, new_inp);
  1034. }
  1035. return replace_inps_to_nchw4(opr, new_inp);
  1036. };
  1037. auto replace_resize_opr = [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1038. OperatorNodeBase* opr,
  1039. const VarNodeArray new_inp) {
  1040. using Param = opr::ResizeForward::Param;
  1041. using Format = Param::Format;
  1042. mgb_assert(opr->input().size() == new_inp.size());
  1043. auto& resize = opr->cast_final_safe<opr::ResizeForward>();
  1044. if (resize.param().format != Format::NCHW4) {
  1045. return replace_non_nchw4_opr(opr, new_inp);
  1046. }
  1047. return replace_inps_to_nchw4(opr, new_inp);
  1048. };
  1049. auto replace_pooling_opr = [replace_non_nchw4_opr](
  1050. OperatorNodeBase* opr,
  1051. const VarNodeArray new_inp) {
  1052. using Param = opr::PoolingForward::Param;
  1053. using Format = Param::Format;
  1054. mgb_assert(opr->input().size() == new_inp.size());
  1055. auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
  1056. if (pooling.param().format != Format::NCHW4) {
  1057. return replace_non_nchw4_opr(opr, new_inp);
  1058. }
  1059. size_t nr_inps = opr->input().size();
  1060. MGB_MARK_USED_VAR(nr_inps);
  1061. mgb_assert(nr_inps == 1);
  1062. size_t nr_channels = opr->input(0)->shape()[1] * 4;
  1063. if (nr_channels % 32 == 0) { // use nchw32 format
  1064. VarNode* new_inp_var = new_inp[0];
  1065. if (opr->input(0)->shape().eq_shape(new_inp[0]->shape())) {
  1066. new_inp_var =
  1067. RelayoutPlaceholder::make(
  1068. new_inp[0], RelayoutPlaceholder::LayoutType::
  1069. NCHW4_TO_NCHW32)
  1070. .node();
  1071. } else {
  1072. mgb_assert(opr->input(0)->shape().ndim == 5 &&
  1073. opr->input(0)->shape()[4] == 4);
  1074. mgb_assert(new_inp[0]->shape().ndim == 5 &&
  1075. new_inp[0]->shape()[4] == 32);
  1076. }
  1077. auto new_param = pooling.param();
  1078. new_param.format = Format::NCHW32;
  1079. auto new_pooling = opr::PoolingForward::make(new_inp_var, new_param,
  1080. opr->config());
  1081. return new_pooling.node()->owner_opr();
  1082. }
  1083. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1084. };
  1085. auto ret = std::make_unique<EnableTensorCorePass>();
  1086. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  1087. auto&& replace_func = ret->m_opr_replace_func;
  1088. replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;
  1089. // elemwise like
  1090. replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
  1091. replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
  1092. replace_func[opr::ElemwiseMultiType::typeinfo()] =
  1093. replace_elemwise_like_opr;
  1094. replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;
  1095. // format aware
  1096. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  1097. replace_func[opr::WarpAffineForward::typeinfo()] = replace_warp_affine_opr;
  1098. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  1099. replace_warp_perspective_opr;
  1100. replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
  1101. // to nchw4
  1102. replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw4;
  1103. replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw4;
  1104. replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw4;
  1105. replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw4;
  1106. replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw4;
  1107. return ret;
  1108. MIDOUT_E
  1109. }
  1110. /* ================ EnableCHWN4Pass =============== */
  1111. VarNode* EnableCHWN4Pass::on_graph_endpoint_var(VarNode* new_var,
  1112. VarNode* /* orig_var */) const {
  1113. if (m_varshape_changed.count(new_var)) {
  1114. return RelayoutPlaceholder::make(
  1115. new_var, RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4)
  1116. .node();
  1117. }
  1118. return new_var;
  1119. }
  1120. std::unique_ptr<EnableCHWN4Pass> EnableCHWN4Pass::make_chwn4_converter() {
  1121. MIDOUT_B("EnableCHWN4Pass::make")
  1122. auto ret = std::make_unique<EnableCHWN4Pass>();
  1123. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  1124. auto&& replace_func = ret->m_opr_replace_func;
  1125. auto&& varshape_changed = ret->m_varshape_changed;
  1126. // replace rule for conv bias opr
  1127. auto replace_conv_bias_opr = [&varshape_changed](
  1128. OperatorNodeBase* opr,
  1129. const VarNodeArray& new_inp) {
  1130. using Param = megdnn::param::ConvBias;
  1131. using Format = Param::Format;
  1132. mgb_assert(opr->input().size() == new_inp.size());
  1133. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  1134. if (conv_bias.param().format != Format::NCHW4 ||
  1135. conv_bias.output(0)->dtype().enumv() != DTypeEnum::QuantizedS8) {
  1136. size_t nr_inps = new_inp.size();
  1137. bool shape_has_changed = false;
  1138. for (size_t i = 0; i < nr_inps; ++i) {
  1139. if (varshape_changed.count(new_inp[i])) {
  1140. shape_has_changed = true;
  1141. break;
  1142. }
  1143. }
  1144. mgb_assert(
  1145. !shape_has_changed,
  1146. "EnableCHWN4Pass assumes that the shape of inputs of"
  1147. "ConvBias operators whose output dtype is not QuantizedS8 "
  1148. "can not be changed in this opt pass");
  1149. return serialization::copy_opr_shallow(*opr, new_inp,
  1150. opr->config());
  1151. }
  1152. mgb_assert(varshape_changed.count(new_inp[1]) == 0,
  1153. "EnableCHWN4Pass assumes that filter tensor of "
  1154. "conv_bias operator can not be changed by other operators");
  1155. VarNode *src = nullptr, *weight = nullptr, *bias = nullptr,
  1156. *z_inp = nullptr;
  1157. // process src tensor
  1158. if (varshape_changed.count(new_inp[0]) ==
  1159. 0) { // new input is NCHW4 layout
  1160. // currently not support group conv
  1161. auto symvar = RelayoutPlaceholder::make(
  1162. new_inp[0],
  1163. RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
  1164. src = symvar.node();
  1165. } else { // new input is NCHW32 layout
  1166. src = new_inp[0];
  1167. }
  1168. // process weight tensor
  1169. {
  1170. auto symvar = RelayoutPlaceholder::make(
  1171. new_inp[1],
  1172. RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
  1173. weight = symvar.node();
  1174. }
  1175. if (new_inp.size() == 2) {
  1176. auto param = conv_bias.param();
  1177. param.format = Format::CHWN4;
  1178. auto new_opr = opr::ConvBiasForward::make(
  1179. src, weight, param, conv_bias.execution_policy(),
  1180. conv_bias.config());
  1181. varshape_changed.insert(new_opr.node());
  1182. return new_opr.node()->owner_opr();
  1183. }
  1184. auto process_inp = [&](VarNode* inp) -> VarNode* {
  1185. if (varshape_changed.count(inp) == 0) {
  1186. auto symvar = RelayoutPlaceholder::make(
  1187. inp, RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
  1188. return symvar.node();
  1189. } else {
  1190. return inp;
  1191. }
  1192. };
  1193. // process bias tensor
  1194. bias = process_inp(new_inp[2]);
  1195. if (new_inp.size() == 3) {
  1196. auto param = conv_bias.param();
  1197. param.format = Format::CHWN4;
  1198. auto new_opr = opr::ConvBiasForward::make(
  1199. src, weight, bias, param, conv_bias.execution_policy(),
  1200. conv_bias.config());
  1201. varshape_changed.insert(new_opr.node());
  1202. return new_opr.node()->owner_opr();
  1203. }
  1204. // process z_inp tensor
  1205. z_inp = process_inp(new_inp[3]);
  1206. auto param = conv_bias.param();
  1207. param.format = Format::CHWN4;
  1208. auto new_opr = opr::ConvBiasForward::make(
  1209. src, weight, bias, z_inp, param, conv_bias.execution_policy(),
  1210. conv_bias.config());
  1211. varshape_changed.insert(new_opr.node());
  1212. return new_opr.node()->owner_opr();
  1213. };
  1214. // replace rule for elemwise like opr
  1215. // for oprs support NCHW4 and CHWN4 layout
  1216. auto replace_elemwise_like_opr = [&varshape_changed](
  1217. OperatorNodeBase* opr,
  1218. const VarNodeArray new_inp) {
  1219. mgb_assert(opr->input().size() == new_inp.size());
  1220. size_t nr_inps = new_inp.size();
  1221. size_t nr_shape_changed = 0;
  1222. for (size_t i = 0; i < nr_inps; ++i) {
  1223. if (varshape_changed.count(new_inp[i])) {
  1224. nr_shape_changed++;
  1225. }
  1226. }
  1227. if (nr_shape_changed) {
  1228. auto inps = new_inp;
  1229. if (nr_shape_changed >=
  1230. nr_inps / 2) { // CHWN4 > NCHW4 -> use CHWN4
  1231. for (size_t i = 0; i < nr_inps; ++i) {
  1232. if (varshape_changed.count(new_inp[i]) == 0) {
  1233. auto symvar = RelayoutPlaceholder::make(
  1234. new_inp[i], RelayoutPlaceholder::LayoutType::
  1235. NCHW4_TO_CHWN4);
  1236. inps[i] = symvar.node();
  1237. }
  1238. }
  1239. auto new_opr = serialization::copy_opr_shallow(*opr, inps,
  1240. opr->config());
  1241. varshape_changed.insert(new_opr->output(0));
  1242. return new_opr;
  1243. } else { // CHWN4 < NCHW4 -> use NCHW4
  1244. for (size_t i = 0; i < nr_inps; ++i) {
  1245. if (varshape_changed.count(new_inp[i])) {
  1246. auto symvar = RelayoutPlaceholder::make(
  1247. new_inp[i], RelayoutPlaceholder::LayoutType::
  1248. CHWN4_TO_NCHW4);
  1249. inps[i] = symvar.node();
  1250. }
  1251. }
  1252. return serialization::copy_opr_shallow(*opr, inps,
  1253. opr->config());
  1254. }
  1255. }
  1256. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1257. };
  1258. // for oprs only supports NCHW4 layout
  1259. auto replace_inps_to_nchw4 = [&varshape_changed](
  1260. OperatorNodeBase* opr,
  1261. const VarNodeArray new_inp) {
  1262. mgb_assert(opr->input().size() == new_inp.size());
  1263. VarNodeArray inps = new_inp;
  1264. for (size_t i = 0; i < opr->input().size(); ++i) {
  1265. if (varshape_changed.count(new_inp[i])) {
  1266. auto symvar = RelayoutPlaceholder::make(
  1267. new_inp[i],
  1268. RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4);
  1269. inps[i] = symvar.node();
  1270. }
  1271. }
  1272. auto new_opr =
  1273. serialization::copy_opr_shallow(*opr, inps, opr->config());
  1274. return new_opr;
  1275. };
  1276. auto replace_non_nchw4_opr = [&varshape_changed](
  1277. OperatorNodeBase* opr,
  1278. const VarNodeArray new_inp) {
  1279. size_t nr_inps = opr->input().size();
  1280. bool shape_has_changed = false;
  1281. for (size_t i = 0; i < nr_inps; ++i) {
  1282. if (varshape_changed.count(new_inp[i])) {
  1283. shape_has_changed = true;
  1284. }
  1285. }
  1286. mgb_assert(!shape_has_changed,
  1287. "EnableCHWN4Pass assumes that inputs' shape of "
  1288. "non-nchw4 operators "
  1289. "can not be changed in this opt "
  1290. "pass");
  1291. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1292. };
  1293. // capture by copy to avoid use after return
  1294. auto replace_warp_affine_opr =
  1295. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1296. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1297. using Param = opr::WarpAffineForward::Param;
  1298. using Format = Param::Format;
  1299. mgb_assert(opr->input().size() == new_inp.size());
  1300. auto& warp = opr->cast_final_safe<opr::WarpAffineForward>();
  1301. if (warp.param().format != Format::NCHW4) {
  1302. return replace_non_nchw4_opr(opr, new_inp);
  1303. }
  1304. return replace_inps_to_nchw4(opr, new_inp);
  1305. };
  1306. auto replace_warp_perspective_opr =
  1307. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1308. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1309. using Param = opr::WarpPerspectiveForward::Param;
  1310. using Format = Param::Format;
  1311. mgb_assert(opr->input().size() == new_inp.size());
  1312. auto& warp =
  1313. opr->cast_final_safe<opr::WarpPerspectiveForward>();
  1314. if (warp.param().format != Format::NCHW4) {
  1315. return replace_non_nchw4_opr(opr, new_inp);
  1316. }
  1317. return replace_inps_to_nchw4(opr, new_inp);
  1318. };
  1319. auto replace_resize_opr = [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1320. OperatorNodeBase* opr,
  1321. const VarNodeArray new_inp) {
  1322. using Param = opr::ResizeForward::Param;
  1323. using Format = Param::Format;
  1324. mgb_assert(opr->input().size() == new_inp.size());
  1325. auto& resize = opr->cast_final_safe<opr::ResizeForward>();
  1326. if (resize.param().format != Format::NCHW4) {
  1327. return replace_non_nchw4_opr(opr, new_inp);
  1328. }
  1329. return replace_inps_to_nchw4(opr, new_inp);
  1330. };
  1331. auto replace_pooling_opr = [&varshape_changed, replace_non_nchw4_opr](
  1332. OperatorNodeBase* opr,
  1333. const VarNodeArray new_inp) {
  1334. using Param = opr::PoolingForward::Param;
  1335. using Format = Param::Format;
  1336. mgb_assert(opr->input().size() == new_inp.size());
  1337. auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
  1338. if (pooling.param().format != Format::NCHW4) {
  1339. return replace_non_nchw4_opr(opr, new_inp);
  1340. }
  1341. size_t nr_inps = opr->input().size();
  1342. MGB_MARK_USED_VAR(nr_inps);
  1343. mgb_assert(nr_inps == 1);
  1344. if (varshape_changed.count(new_inp[0])) {
  1345. auto new_param = pooling.param();
  1346. new_param.format = Format::CHWN4;
  1347. auto new_pooling = opr::PoolingForward::make(new_inp[0], new_param,
  1348. opr->config());
  1349. varshape_changed.insert(new_pooling.node());
  1350. return new_pooling.node()->owner_opr();
  1351. }
  1352. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1353. };
  1354. replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;
  1355. // elemwise like
  1356. replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
  1357. replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
  1358. replace_func[opr::ElemwiseMultiType::typeinfo()] =
  1359. replace_elemwise_like_opr;
  1360. replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;
  1361. // format aware
  1362. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  1363. replace_func[opr::WarpAffineForward::typeinfo()] = replace_warp_affine_opr;
  1364. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  1365. replace_warp_perspective_opr;
  1366. replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
  1367. // to nchw4
  1368. replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw4;
  1369. replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw4;
  1370. replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw4;
  1371. replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw4;
  1372. replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw4;
  1373. replace_func[opr::BatchConvBias::typeinfo()] = replace_inps_to_nchw4;
  1374. return ret;
  1375. MIDOUT_E
  1376. }
  1377. /* ================ EnableNCHW4Pass ================ */
  1378. VarNode* EnableNCHW4Pass::on_graph_endpoint_var(VarNode* new_var,
  1379. VarNode* orig_var) const {
  1380. if (!orig_var->shape().eq_shape(new_var->shape())) {
  1381. return RelayoutPlaceholder::make(
  1382. new_var, RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
  1383. .node();
  1384. }
  1385. return new_var;
  1386. }
  1387. //! FIXME: All float oprs do not support NCHW4. Supports it in the future plz.
  1388. std::unique_ptr<EnableNCHW4Pass> EnableNCHW4Pass::make_nchw4_converter() {
  1389. MIDOUT_B("EnableNCHW4Pass::make")
  1390. auto ret = std::make_unique<EnableNCHW4Pass>();
  1391. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  1392. using RelayoutMode = RelayoutPlaceholder::LayoutType;
  1393. megdnn::param::Convolution::Format conv_format =
  1394. megdnn::param::Convolution::Format::NCHW4;
  1395. megdnn::param::ConvBias::Format conv_bias_format =
  1396. megdnn::param::ConvBias::Format::NCHW4;
  1397. megdnn::param::BatchConvBias::Format batch_conv_bias_format =
  1398. megdnn::param::BatchConvBias::Format::NCHW4;
  1399. RelayoutMode src_to_nchw4_mode = RelayoutMode::NCHW_TO_NCHW4;
  1400. RelayoutMode src_to_nchw_mode = RelayoutMode::NCHW4_TO_NCHW;
  1401. RelayoutMode weight_to_nchw4_mode_dense =
  1402. RelayoutMode::WEIGHT_NCHW_TO_NCHW4_DENSE;
  1403. RelayoutMode weight_to_nchw4_mode_group =
  1404. RelayoutMode::WEIGHT_NCHW_TO_NCHW4_GROUP;
  1405. struct ConvMode {
  1406. RelayoutMode weight;
  1407. RelayoutMode src;
  1408. };
  1409. auto trans_nchw4 =
  1410. [weight_to_nchw4_mode_dense, weight_to_nchw4_mode_group,
  1411. src_to_nchw4_mode](
  1412. const megdnn::param::Convolution::Sparse conv_mode,
  1413. const VarNode* filter) -> ConvMode {
  1414. if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
  1415. mgb_assert(filter->shape().ndim == 4,
  1416. "The origin filter is not NCHW mode");
  1417. size_t IC = filter->shape()[1];
  1418. if (IC < 4) {
  1419. return {RelayoutMode::WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV,
  1420. RelayoutMode::NCHW_TO_NCHW4_IC_SMALL_CONV};
  1421. } else {
  1422. return {weight_to_nchw4_mode_dense, src_to_nchw4_mode};
  1423. }
  1424. } else {
  1425. mgb_assert(conv_mode == megdnn::param::Convolution::Sparse::GROUP);
  1426. mgb_assert(filter->shape().ndim == 5,
  1427. "The origin filter if not NCHW mode");
  1428. size_t IC = filter->shape()[2];
  1429. mgb_assert(IC % 4 == 0,
  1430. "The input channel should be divisible by 4 for group "
  1431. "conv");
  1432. return {weight_to_nchw4_mode_group, src_to_nchw4_mode};
  1433. }
  1434. };
  1435. auto replace_conv_opr = [trans_nchw4, conv_format](
  1436. OperatorNodeBase* opr,
  1437. const VarNodeArray& new_inp) {
  1438. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1439. return serialization::copy_opr_shallow(*opr, new_inp,
  1440. opr->config());
  1441. }
  1442. mgb_assert(opr->input().size() == new_inp.size());
  1443. auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
  1444. if (conv_opr.param().format !=
  1445. megdnn::param::Convolution::Format::NCHW) {
  1446. return serialization::copy_opr_shallow(*opr, new_inp,
  1447. opr->config());
  1448. }
  1449. auto conv_mode = trans_nchw4(conv_opr.param().sparse, new_inp[1]);
  1450. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  1451. // src: NCHW --> NCWH4
  1452. if (new_inp[0]->shape().ndim != 5) {
  1453. mgb_assert(new_inp[0]->shape().ndim == 4);
  1454. auto new_src = RelayoutPlaceholder::make(new_inp[0], conv_mode.src);
  1455. conv_src = new_src.node();
  1456. }
  1457. // weight: NCHW --> NCHW4
  1458. auto new_filter =
  1459. RelayoutPlaceholder::make(new_inp[1], conv_mode.weight);
  1460. conv_filter = new_filter.node();
  1461. // format: NCHW --> NCHW4
  1462. auto new_param = conv_opr.param();
  1463. new_param.format = conv_format;
  1464. // dst
  1465. auto new_conv_opr = opr::Convolution::make(
  1466. conv_src, conv_filter, new_param, conv_opr.execution_policy(),
  1467. conv_opr.config());
  1468. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  1469. mgb_assert(new_conv_opr.shape().ndim == 5,
  1470. "The conv dst dim is not trans to nchw4");
  1471. return new_opr;
  1472. };
  1473. auto replace_batch_conv_bias_opr = [batch_conv_bias_format,
  1474. src_to_nchw4_mode](
  1475. OperatorNodeBase* opr,
  1476. const VarNodeArray& new_inp) {
  1477. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1478. return serialization::copy_opr_shallow(*opr, new_inp,
  1479. opr->config());
  1480. }
  1481. mgb_assert(opr->input().size() == new_inp.size());
  1482. auto& batch_conv_bias_opr =
  1483. opr->cast_final_safe<opr::BatchConvBiasForward>();
  1484. if (batch_conv_bias_opr.param().format !=
  1485. megdnn::param::BatchConvBias::Format::NCHW) {
  1486. return serialization::copy_opr_shallow(*opr, new_inp,
  1487. opr->config());
  1488. }
  1489. mgb_assert(batch_conv_bias_opr.param().format ==
  1490. megdnn::param::BatchConvBias::Format::NCHW,
  1491. "ConvertFormat Pass only support converting NCHW to NCHW4");
  1492. // what should be converted: src, weight
  1493. VarNode *src = new_inp[0], *filter = new_inp[1];
  1494. // src: NCHW --> NCHW4
  1495. if (new_inp[0]->shape().ndim != 5) {
  1496. mgb_assert(new_inp[0]->shape().ndim == 4);
  1497. auto new_src =
  1498. RelayoutPlaceholder::make(new_inp[0], src_to_nchw4_mode);
  1499. src = new_src.node();
  1500. }
  1501. // weight: BNCHW --> BNCHW4
  1502. // only support dense mode, which is similar with conv->group.
  1503. auto weight_mode =
  1504. RelayoutPlaceholder::LayoutType::WEIGHT_NCHW_TO_NCHW4_GROUP;
  1505. auto new_filter = RelayoutPlaceholder::make(new_inp[1], weight_mode);
  1506. filter = new_filter.node();
  1507. // format: NCHW --> NCHW4
  1508. auto new_param = batch_conv_bias_opr.param();
  1509. new_param.format = batch_conv_bias_format;
  1510. if (new_inp.size() == 2) {
  1511. auto dst = opr::BatchConvBias::make(
  1512. src, filter, new_param,
  1513. batch_conv_bias_opr.execution_policy(),
  1514. batch_conv_bias_opr.config());
  1515. OperatorNodeBase* new_opr = dst.node()->owner_opr();
  1516. mgb_assert(dst.shape().ndim == 5,
  1517. "The conv_bias dst dim is not trans to nchw4");
  1518. return new_opr;
  1519. }
  1520. // bias: NCHW --> NCHW4
  1521. VarNode* bias = new_inp[2];
  1522. if (new_inp[2]->shape().ndim == 4) {
  1523. auto new_bias =
  1524. RelayoutPlaceholder::make(new_inp[2], src_to_nchw4_mode);
  1525. bias = new_bias.node();
  1526. }
  1527. if (new_inp.size() == 3) {
  1528. auto dst = opr::BatchConvBias::make(
  1529. src, filter, bias, new_param,
  1530. batch_conv_bias_opr.execution_policy(),
  1531. batch_conv_bias_opr.config());
  1532. OperatorNodeBase* new_opr = dst.node()->owner_opr();
  1533. mgb_assert(dst.shape().ndim == 5,
  1534. "The conv_bias dst dim is not trans to nchw4");
  1535. return new_opr;
  1536. }
  1537. // z_inp: NCHW --> NCHW4
  1538. VarNode* z_inp = new_inp[3];
  1539. if (new_inp[3]->shape().ndim == 4) {
  1540. auto new_z =
  1541. RelayoutPlaceholder::make(new_inp[3], src_to_nchw4_mode);
  1542. z_inp = new_z.node();
  1543. }
  1544. auto dst =
  1545. opr::BatchConvBias::make(src, filter, bias, z_inp, new_param,
  1546. batch_conv_bias_opr.execution_policy(),
  1547. batch_conv_bias_opr.config());
  1548. OperatorNodeBase* new_opr = dst.node()->owner_opr();
  1549. mgb_assert(dst.shape().ndim == 5,
  1550. "The conv_bias dst dim is not trans to nchw4");
  1551. return new_opr;
  1552. };
  1553. auto replace_conv_bias_opr = [trans_nchw4, conv_bias_format,
  1554. src_to_nchw4_mode](
  1555. OperatorNodeBase* opr,
  1556. const VarNodeArray& new_inp) {
  1557. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1558. return serialization::copy_opr_shallow(*opr, new_inp,
  1559. opr->config());
  1560. }
  1561. mgb_assert(opr->input().size() == new_inp.size());
  1562. auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
  1563. if (conv_bias_opr.param().format !=
  1564. megdnn::param::Convolution::Format::NCHW) {
  1565. return serialization::copy_opr_shallow(*opr, new_inp,
  1566. opr->config());
  1567. }
  1568. // what should be converted: src, weight
  1569. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1];
  1570. auto conv_mode = trans_nchw4(conv_bias_opr.param().sparse, new_inp[1]);
  1571. // src: NCHW --> NCHW4
  1572. if (new_inp[0]->shape().ndim != 5) {
  1573. mgb_assert(new_inp[0]->shape().ndim == 4);
  1574. auto new_src = RelayoutPlaceholder::make(new_inp[0], conv_mode.src);
  1575. conv_bias_src = new_src.node();
  1576. }
  1577. // weight: NCHW --> NCHW4 or GNCHW --> GNCHW4
  1578. auto new_filter =
  1579. RelayoutPlaceholder::make(new_inp[1], conv_mode.weight);
  1580. conv_bias_filter = new_filter.node();
  1581. // format: NCHW --> NCHW4
  1582. auto new_param = conv_bias_opr.param();
  1583. new_param.format = conv_bias_format;
  1584. if (new_inp.size() == 2) {
  1585. auto new_conv_bias_opr = opr::ConvBias::make(
  1586. conv_bias_src, conv_bias_filter, new_param,
  1587. conv_bias_opr.execution_policy(), conv_bias_opr.config());
  1588. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  1589. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  1590. "The conv_bias dst dim is not trans to nchw4");
  1591. return new_opr;
  1592. }
  1593. // bias: NCHW --> NCHW4
  1594. VarNode* conv_bias_bias = new_inp[2];
  1595. if (new_inp[2]->shape().ndim == 4) {
  1596. auto new_bias =
  1597. RelayoutPlaceholder::make(new_inp[2], src_to_nchw4_mode);
  1598. conv_bias_bias = new_bias.node();
  1599. }
  1600. if (new_inp.size() == 3) {
  1601. auto new_conv_bias_opr = opr::ConvBias::make(
  1602. conv_bias_src, conv_bias_filter, conv_bias_bias, new_param,
  1603. conv_bias_opr.execution_policy(), conv_bias_opr.config());
  1604. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  1605. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  1606. "The conv_bias dst dim is not trans to nchw4");
  1607. return new_opr;
  1608. }
  1609. // z_inp: NCHW --> NCHW4
  1610. VarNode* z_inp = new_inp[3];
  1611. if (new_inp[3]->shape().ndim == 4) {
  1612. auto new_z =
  1613. RelayoutPlaceholder::make(new_inp[3], src_to_nchw4_mode);
  1614. z_inp = new_z.node();
  1615. }
  1616. auto new_conv_bias_opr = opr::ConvBias::make(
  1617. conv_bias_src, conv_bias_filter, conv_bias_bias, z_inp,
  1618. new_param, conv_bias_opr.execution_policy(),
  1619. conv_bias_opr.config());
  1620. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  1621. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  1622. "The conv_bias dst dim is not trans to nchw4");
  1623. return new_opr;
  1624. };
  1625. auto replace_elemwise_opr = [=](OperatorNodeBase* opr,
  1626. const VarNodeArray& new_inp) {
  1627. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1628. return serialization::copy_opr_shallow(*opr, new_inp,
  1629. opr->config());
  1630. }
  1631. mgb_assert(opr->input().size() == new_inp.size());
  1632. bool has_inp_changed = false;
  1633. for (size_t i = 0; i < opr->input().size(); i++) {
  1634. if (new_inp[i]->shape().ndim == 5) {
  1635. has_inp_changed = true;
  1636. break;
  1637. }
  1638. }
  1639. if (has_inp_changed) {
  1640. auto temp_inp = new_inp;
  1641. for (size_t i = 0; i < opr->input().size(); i++) {
  1642. if (new_inp[i]->shape().ndim == 4) {
  1643. auto new_var = RelayoutPlaceholder::make(new_inp[i],
  1644. src_to_nchw4_mode);
  1645. temp_inp[i] = new_var.node();
  1646. } else {
  1647. mgb_assert((new_inp[i]->shape().ndim == 5) ||
  1648. new_inp[i]->shape().is_scalar());
  1649. }
  1650. }
  1651. return serialization::copy_opr_shallow(*opr, temp_inp,
  1652. opr->config());
  1653. } else {
  1654. return serialization::copy_opr_shallow(*opr, new_inp,
  1655. opr->config());
  1656. }
  1657. };
  1658. auto relayout_inp_to_nchw = [=](OperatorNodeBase* opr,
  1659. const VarNodeArray& new_inp) {
  1660. mgb_assert(opr->input().size() == new_inp.size());
  1661. VarNodeArray temp_inp = new_inp;
  1662. for (size_t i = 0; i < opr->input().size(); i++) {
  1663. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1664. mgb_assert(opr->input(i)->shape().ndim == 4);
  1665. mgb_assert(new_inp[i]->shape().ndim == 5);
  1666. auto new_var =
  1667. RelayoutPlaceholder::make(new_inp[i], src_to_nchw_mode);
  1668. temp_inp[i] = new_var.node();
  1669. }
  1670. }
  1671. return serialization::copy_opr_shallow(*opr, temp_inp, opr->config());
  1672. };
  1673. auto replace_pooling_opr = [](OperatorNodeBase* opr,
  1674. const VarNodeArray& new_inp) {
  1675. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1676. return serialization::copy_opr_shallow(*opr, new_inp,
  1677. opr->config());
  1678. }
  1679. using Param = opr::PoolingForward::Param;
  1680. using Format = Param::Format;
  1681. mgb_assert(opr->input().size() == new_inp.size());
  1682. auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
  1683. if (pooling.param().format != Format::NCHW) {
  1684. return opr;
  1685. }
  1686. if (new_inp[0]->shape().ndim == 5) {
  1687. mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
  1688. auto new_param = pooling.param();
  1689. new_param.format = Format::NCHW4;
  1690. auto new_pooling = opr::PoolingForward::make(new_inp[0], new_param,
  1691. opr->config());
  1692. mgb_assert(new_pooling.shape().ndim == 5,
  1693. "out var of Pooling opr after transform must be 5 (got: "
  1694. "%zu).",
  1695. new_pooling.shape().ndim);
  1696. return new_pooling.node()->owner_opr();
  1697. }
  1698. auto new_opr =
  1699. serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1700. return new_opr;
  1701. };
  1702. auto replace_resize_opr = [](OperatorNodeBase* opr,
  1703. const VarNodeArray& new_inp) {
  1704. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1705. return serialization::copy_opr_shallow(*opr, new_inp,
  1706. opr->config());
  1707. }
  1708. using Param = opr::ResizeForward::Param;
  1709. using Format = Param::Format;
  1710. mgb_assert(opr->input().size() == new_inp.size());
  1711. auto& resize = opr->cast_final_safe<opr::ResizeForward>();
  1712. if (new_inp[0]->shape().ndim == 5) {
  1713. mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
  1714. auto new_param = resize.param();
  1715. new_param.format = Format::NCHW4;
  1716. auto new_resize = opr::ResizeForward::make(
  1717. new_inp[0], new_inp[1], new_param, opr->config());
  1718. mgb_assert(new_resize.shape().ndim == 5,
  1719. "out var of Resize opr after transform must be 5 (got: "
  1720. "%zu).",
  1721. new_resize.shape().ndim);
  1722. return new_resize.node()->owner_opr();
  1723. }
  1724. auto new_opr =
  1725. serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1726. return new_opr;
  1727. };
  1728. auto replace_warp_perspective_opr = [](OperatorNodeBase* opr,
  1729. const VarNodeArray& new_inp) {
  1730. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1731. return serialization::copy_opr_shallow(*opr, new_inp,
  1732. opr->config());
  1733. }
  1734. using Param = opr::WarpPerspective::Param;
  1735. using Format = Param::Format;
  1736. mgb_assert(opr->input().size() == new_inp.size());
  1737. auto& warp = opr->cast_final_safe<opr::WarpPerspectiveForward>();
  1738. if (new_inp[0]->shape().ndim == 5) {
  1739. mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
  1740. auto new_param = warp.param();
  1741. new_param.format = Format::NCHW4;
  1742. SymbolVar new_warp;
  1743. if (new_inp.size() == 3) {
  1744. new_warp = opr::WarpPerspectiveForward::make(
  1745. new_inp[0], new_inp[1], nullptr, new_inp[2], new_param,
  1746. opr->config());
  1747. } else {
  1748. mgb_assert(new_inp.size() == 4);
  1749. new_warp = opr::WarpPerspectiveForward::make(
  1750. new_inp[0], new_inp[1], new_inp[2], new_inp[3],
  1751. new_param, opr->config());
  1752. }
  1753. mgb_assert(new_warp.shape().ndim == 5,
  1754. "out var of WarpPerspective opr after transform must be "
  1755. "5 (got: "
  1756. "%zu).",
  1757. new_warp.shape().ndim);
  1758. return new_warp.node()->owner_opr();
  1759. }
  1760. auto new_opr =
  1761. serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1762. return new_opr;
  1763. };
  1764. auto&& replace_func = ret->m_opr_replace_func;
  1765. //! supportted nchw4
  1766. replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
  1767. replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
  1768. replace_func[opr::BatchConvBias::typeinfo()] = replace_batch_conv_bias_opr;
  1769. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  1770. replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
  1771. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  1772. replace_warp_perspective_opr;
  1773. replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_opr;
  1774. replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_opr;
  1775. replace_func[opr::ElemwiseMultiType::typeinfo()] = replace_elemwise_opr;
  1776. replace_func[opr::PowC::typeinfo()] = replace_elemwise_opr;
  1777. //! not supported nchw4
  1778. replace_func[opr::Concat::typeinfo()] = relayout_inp_to_nchw;
  1779. replace_func[opr::ConvolutionBackwardData::typeinfo()] =
  1780. relayout_inp_to_nchw;
  1781. replace_func[opr::Subtensor::typeinfo()] = relayout_inp_to_nchw;
  1782. replace_func[opr::GetVarShape::typeinfo()] = relayout_inp_to_nchw;
  1783. replace_func[opr::Dimshuffle::typeinfo()] = relayout_inp_to_nchw;
  1784. replace_func[opr::Reduce::typeinfo()] = relayout_inp_to_nchw;
  1785. replace_func[opr::AssertEqual::typeinfo()] = relayout_inp_to_nchw;
  1786. replace_func[opr::IncrSubtensor::typeinfo()] = relayout_inp_to_nchw;
  1787. replace_func[opr::WarpAffineForward::typeinfo()] = relayout_inp_to_nchw;
  1788. return ret;
  1789. MIDOUT_E
  1790. }
  1791. /* ================ EnableNchwxxPass =============== */
  1792. VarNode* EnableNchwxxPass::on_graph_endpoint_var(VarNode* new_var,
  1793. VarNode* orig_var) const {
  1794. if (!orig_var->shape().eq_shape(new_var->shape())) {
  1795. if (m_pack_c_size == 8) {
  1796. return RelayoutPlaceholder::make(
  1797. new_var,
  1798. RelayoutPlaceholder::LayoutType::NCHW88_TO_NCHW)
  1799. .node();
  1800. } else if (m_pack_c_size == 4) {
  1801. return RelayoutPlaceholder::make(
  1802. new_var,
  1803. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
  1804. .node();
  1805. }
  1806. }
  1807. return new_var;
  1808. }
  1809. static inline TensorShape nchwxx_shape_2_nchw_shape(
  1810. const TensorShape& origin_shape) {
  1811. mgb_assert(origin_shape.ndim == 5);
  1812. TensorShape result = origin_shape;
  1813. result[1] *= result[4];
  1814. result.ndim = 4;
  1815. return result;
  1816. }
  1817. template <typename OprType>
  1818. static inline bool nchw_nchwxx_valid(
  1819. const OprType& opr, const VarNodeArray& new_inp, const size_t pack_size,
  1820. megdnn::param::ConvBias::NonlineMode nonline_mode =
  1821. megdnn::param::ConvBias::NonlineMode::IDENTITY,
  1822. bool is_dot = false) {
  1823. auto& src_node = new_inp[0];
  1824. auto& filter_node = new_inp[1];
  1825. auto dst_node = opr.output(0);
  1826. //! already transformed or have fuse Z
  1827. if (filter_node->shape().ndim != 4 || new_inp.size() == 4) {
  1828. return false;
  1829. }
  1830. megdnn::ConvolutionBase<megdnn::param::Convolution>::CanonizedFilterMeta fm;
  1831. fm.format = megdnn::param::Convolution::Format::NCHW;
  1832. fm.should_flip =
  1833. opr.param().mode == megdnn::ConvBiasForward::Mode::CONVOLUTION;
  1834. fm.group = 1;
  1835. fm.spatial_ndim = 2;
  1836. fm.ocpg = filter_node->shape()[0];
  1837. fm.icpg = filter_node->shape()[1];
  1838. fm.spatial[0] = filter_node->shape()[2];
  1839. fm.spatial[1] = filter_node->shape()[3];
  1840. fm.stride[0] = opr.param().stride_h;
  1841. fm.stride[1] = opr.param().stride_w;
  1842. fm.padding[0] = opr.param().pad_h;
  1843. fm.padding[1] = opr.param().pad_w;
  1844. fm.dilation[0] = opr.param().dilate_h;
  1845. fm.dilation[1] = opr.param().dilate_w;
  1846. megdnn::ConvBiasForward::BiasMode bias_mode =
  1847. megdnn::ConvBiasForward::BiasMode::NO_BIAS;
  1848. if (std::is_same<OprType, opr::ConvBiasForward>::value &&
  1849. new_inp.size() > 2) {
  1850. TensorShape bias_shape = new_inp[2]->shape();
  1851. if (bias_shape.ndim == 5) {
  1852. bias_shape = nchwxx_shape_2_nchw_shape(bias_shape);
  1853. }
  1854. if (bias_shape.ndim == 0) {
  1855. bias_mode = megdnn::ConvBiasForward::BiasMode::NO_BIAS;
  1856. } else if (bias_shape.eq_shape(dst_node->shape())) {
  1857. bias_mode = megdnn::ConvBiasForward::BiasMode::BIAS;
  1858. } else {
  1859. //! just check the ndim, the detail shape check is in check_exec
  1860. mgb_assert(bias_shape.ndim == dst_node->shape().ndim);
  1861. bias_mode =
  1862. megdnn::ConvBiasForward::BiasMode::BROADCAST_CHANNEL_BIAS;
  1863. }
  1864. }
  1865. if (pack_size == 4) {
  1866. if (is_dot && filter_node->dtype().enumv() == DTypeEnum::QuantizedS8) {
  1867. fm.format = megdnn::param::Convolution::Format::NCHW44_DOT;
  1868. } else {
  1869. fm.format = megdnn::param::Convolution::Format::NCHW44;
  1870. }
  1871. } else if (pack_size == 8) {
  1872. fm.format = megdnn::param::Convolution::Format::NCHW88;
  1873. } else {
  1874. mgb_assert(0, "only support nchw44 nchw88");
  1875. }
  1876. return megdnn::ConvBiasForward::is_nchw_nchwxx_optimized(
  1877. src_node->dtype().enumv(), filter_node->dtype().enumv(),
  1878. dst_node->dtype().enumv(), fm, bias_mode, nonline_mode);
  1879. }
  1880. void EnableNchwxxPass::fill_opr_convert_fun(size_t pack_c_size) {
  1881. using RelayoutMode = RelayoutPlaceholder::LayoutType;
  1882. using TestFilterResult = std::pair<TransType, RelayoutMode>;
  1883. RelayoutMode weight_to_nchwxx_mode_dense =
  1884. RelayoutMode::WEIGHT_NCHW_TO_NCHW88_DENSE;
  1885. RelayoutMode weight_to_nchwxx_mode_group =
  1886. RelayoutMode::WEIGHT_NCHW_TO_NCHW88_GROUP;
  1887. RelayoutMode weight_to_nchwxx_mode_chan =
  1888. RelayoutMode::WEIGHT_NCHW_TO_NCHW88_CHAN;
  1889. RelayoutMode hybrid_nchw_nchwxx = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW88;
  1890. RelayoutMode src_to_nchwxx_mode = RelayoutMode::NCHW_TO_NCHW88;
  1891. RelayoutMode src_to_nchw_mode = RelayoutMode::NCHW88_TO_NCHW;
  1892. megdnn::param::ConvBias::Format conv_bias_format =
  1893. megdnn::param::ConvBias::Format::NCHW88;
  1894. megdnn::param::Convolution::Format conv_format =
  1895. megdnn::param::ConvolutionV0::Format::NCHW88;
  1896. megdnn::param::Pooling::Format pooling_format =
  1897. megdnn::param::Pooling::Format::NCHW88;
  1898. std::string convter_pass_name = "conv_format_nchw88";
  1899. if (pack_c_size == 4) {
  1900. weight_to_nchwxx_mode_dense = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DENSE;
  1901. weight_to_nchwxx_mode_group = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_GROUP;
  1902. weight_to_nchwxx_mode_chan = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_CHAN;
  1903. hybrid_nchw_nchwxx = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW44;
  1904. src_to_nchwxx_mode = RelayoutMode::NCHW_TO_NCHW4;
  1905. src_to_nchw_mode = RelayoutMode::NCHW4_TO_NCHW;
  1906. conv_bias_format = megdnn::param::ConvBias::Format::NCHW44;
  1907. conv_format = megdnn::param::ConvolutionV0::Format::NCHW44;
  1908. pooling_format = megdnn::param::Pooling::Format::NCHW44;
  1909. convter_pass_name = "conv_format_nchw44";
  1910. }
  1911. auto test_trans_nchwxx =
  1912. [pack_c_size, weight_to_nchwxx_mode_dense,
  1913. weight_to_nchwxx_mode_group, weight_to_nchwxx_mode_chan,
  1914. hybrid_nchw_nchwxx](
  1915. const megdnn::param::Convolution::Sparse conv_mode,
  1916. const VarNode* filter, const size_t stride_h,
  1917. const size_t stride_w,
  1918. bool valid_nchw_nchw44) -> TestFilterResult {
  1919. TestFilterResult ret{TransType::TRANS_NONE, {}};
  1920. if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
  1921. size_t OC = filter->shape()[0];
  1922. size_t IC = filter->shape()[1];
  1923. if ((IC % pack_c_size == 0) && (OC % pack_c_size == 0)) {
  1924. ret.first = TransType::TRANS_PURE_NCHWXX;
  1925. ret.second = weight_to_nchwxx_mode_dense;
  1926. } else if (valid_nchw_nchw44) {
  1927. ret.first = TransType::TRANS_HYBIRD_NCHWXX;
  1928. ret.second = hybrid_nchw_nchwxx;
  1929. }
  1930. } else {
  1931. mgb_assert(conv_mode == megdnn::param::Convolution::Sparse::GROUP);
  1932. size_t group = filter->shape()[0];
  1933. size_t ocpg = filter->shape()[1];
  1934. size_t icpg = filter->shape()[2];
  1935. if (icpg == 1 && ocpg == 1 && (group % pack_c_size == 0)) {
  1936. ret.first = TransType::TRANS_PURE_NCHWXX;
  1937. ret.second = weight_to_nchwxx_mode_chan;
  1938. } else if ((icpg % pack_c_size == 0) && (ocpg % pack_c_size == 0)) {
  1939. ret.first = TransType::TRANS_PURE_NCHWXX;
  1940. ret.second = weight_to_nchwxx_mode_group;
  1941. }
  1942. }
  1943. return ret;
  1944. };
  1945. auto replace_conv_opr = [test_trans_nchwxx, conv_format, src_to_nchwxx_mode,
  1946. src_to_nchw_mode,
  1947. pack_c_size](OperatorNodeBase* opr,
  1948. const VarNodeArray& new_inp) {
  1949. mgb_assert(opr->input().size() == new_inp.size());
  1950. auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
  1951. mgb_assert(conv_opr.param().format ==
  1952. megdnn::param::Convolution::Format::NCHW,
  1953. "ConvertFormat Pass only support converting NCHW to NCHWXX");
  1954. bool valid_nchw_nchw44 =
  1955. nchw_nchwxx_valid(conv_opr, new_inp, pack_c_size);
  1956. auto is_trans = test_trans_nchwxx(
  1957. conv_opr.param().sparse, new_inp[1], conv_opr.param().stride_h,
  1958. conv_opr.param().stride_w, valid_nchw_nchw44);
  1959. //! can not trans to nchwxx
  1960. if (is_trans.first == TransType::TRANS_NONE) {
  1961. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  1962. new_inp[1]->shape().ndim == 5,
  1963. "The origin filter is not NCHW mode");
  1964. VarNodeArray temp_inp = new_inp;
  1965. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  1966. if (temp_inp[0]->shape().ndim == 5) {
  1967. auto new_src =
  1968. RelayoutPlaceholder::make(new_inp[0], src_to_nchw_mode);
  1969. temp_inp[0] = new_src.node();
  1970. }
  1971. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  1972. opr->config());
  1973. return new_opr;
  1974. } else if (is_trans.first == TransType::TRANS_PURE_NCHWXX) {
  1975. //! filter trans to nchwxx mode
  1976. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  1977. new_inp[1]->shape().ndim == 5,
  1978. "The origin filter is not NCHW mode");
  1979. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  1980. auto new_filter =
  1981. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  1982. conv_filter = new_filter.node();
  1983. //! src trans to nchwxx mode
  1984. if (new_inp[0]->shape().ndim != 5) {
  1985. mgb_assert(new_inp[0]->shape().ndim == 4);
  1986. auto new_src = RelayoutPlaceholder::make(new_inp[0],
  1987. src_to_nchwxx_mode);
  1988. conv_src = new_src.node();
  1989. }
  1990. auto new_param = conv_opr.param();
  1991. new_param.format = conv_format;
  1992. mgb_assert(conv_src->shape().ndim == 5 &&
  1993. conv_filter->shape().ndim >= 6,
  1994. "The conv src dim is not trans to nchwxx");
  1995. auto new_conv_opr = opr::Convolution::make(
  1996. conv_src, conv_filter, new_param,
  1997. conv_opr.execution_policy(), conv_opr.config());
  1998. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  1999. mgb_assert(new_conv_opr.shape().ndim == 5,
  2000. "The conv dst dim is not trans to nchwxx");
  2001. return new_opr;
  2002. } else {
  2003. mgb_assert(is_trans.first == TransType::TRANS_HYBIRD_NCHWXX);
  2004. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  2005. auto new_filter =
  2006. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  2007. conv_filter = new_filter.node();
  2008. mgb_assert(conv_src->shape().ndim == 4 &&
  2009. conv_filter->shape().ndim == 5,
  2010. "The src and filter is OK");
  2011. auto new_param = conv_opr.param();
  2012. new_param.format = conv_format;
  2013. auto new_conv_opr = opr::Convolution::make(
  2014. conv_src, conv_filter, new_param,
  2015. conv_opr.execution_policy(), conv_opr.config());
  2016. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  2017. mgb_assert(new_conv_opr.shape().ndim == 5,
  2018. "The conv dst dim is not trans to nchwxx");
  2019. return new_opr;
  2020. }
  2021. };
  2022. auto replace_conv_bias_opr = [test_trans_nchwxx, conv_bias_format,
  2023. src_to_nchwxx_mode, src_to_nchw_mode,
  2024. pack_c_size](OperatorNodeBase* opr,
  2025. const VarNodeArray& new_inp) {
  2026. mgb_assert(opr->input().size() == new_inp.size());
  2027. mgb_assert(opr->input().size() <= 3,
  2028. "nchwxx does not support conv_bias fuse Z right now");
  2029. auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
  2030. mgb_assert(conv_bias_opr.param().format ==
  2031. megdnn::param::ConvBias::Format::NCHW,
  2032. "ConvertFormat Pass only support converting NCHW to NCHWXX");
  2033. bool valid_nchw_nchw44 =
  2034. nchw_nchwxx_valid(conv_bias_opr, new_inp, pack_c_size,
  2035. conv_bias_opr.param().nonlineMode);
  2036. auto is_trans = test_trans_nchwxx(
  2037. conv_bias_opr.param().sparse, new_inp[1],
  2038. conv_bias_opr.param().stride_h, conv_bias_opr.param().stride_w,
  2039. valid_nchw_nchw44);
  2040. //! can not trans to nchwxx
  2041. if (is_trans.first == TransType::TRANS_NONE) {
  2042. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2043. new_inp[1]->shape().ndim == 5,
  2044. "The origin filter is not NCHW mode");
  2045. VarNodeArray temp_inp = new_inp;
  2046. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  2047. if (temp_inp[0]->shape().ndim == 5) {
  2048. auto new_src =
  2049. RelayoutPlaceholder::make(new_inp[0], src_to_nchw_mode);
  2050. temp_inp[0] = new_src.node();
  2051. }
  2052. //! the bias is nchwxx
  2053. if (new_inp.size() > 2 && temp_inp[2]->shape().ndim == 5) {
  2054. auto new_bias =
  2055. RelayoutPlaceholder::make(new_inp[2], src_to_nchw_mode);
  2056. temp_inp[2] = new_bias.node();
  2057. }
  2058. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  2059. opr->config());
  2060. return new_opr;
  2061. } else if (is_trans.first == TransType::TRANS_PURE_NCHWXX) {
  2062. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2063. *conv_bias_bias = nullptr;
  2064. //! filter trans to nchwxx mode
  2065. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2066. new_inp[1]->shape().ndim == 5,
  2067. "The origin filter is not NCHW mode");
  2068. auto new_filter =
  2069. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  2070. conv_bias_filter = new_filter.node();
  2071. //! src trans to nchwxx mode
  2072. if (new_inp[0]->shape().ndim != 5) {
  2073. mgb_assert(new_inp[0]->shape().ndim == 4);
  2074. auto new_src = RelayoutPlaceholder::make(new_inp[0],
  2075. src_to_nchwxx_mode);
  2076. conv_bias_src = new_src.node();
  2077. }
  2078. //! bias trans to nchwxx mode
  2079. if (new_inp.size() > 2) {
  2080. if (new_inp[2]->shape().ndim == 4) {
  2081. auto new_bias = RelayoutPlaceholder::make(
  2082. new_inp[2], src_to_nchwxx_mode);
  2083. conv_bias_bias = new_bias.node();
  2084. } else {
  2085. mgb_assert(new_inp[2]->shape().ndim == 5);
  2086. conv_bias_bias = new_inp[2];
  2087. }
  2088. }
  2089. auto new_param = conv_bias_opr.param();
  2090. new_param.format = conv_bias_format;
  2091. mgb_assert(conv_bias_src->shape().ndim == 5 &&
  2092. conv_bias_filter->shape().ndim >= 6,
  2093. "The conv_bias src dim is not trans to nchwxx");
  2094. SymbolVar new_conv_bias_opr;
  2095. if (conv_bias_bias) {
  2096. new_conv_bias_opr = opr::ConvBias::make(
  2097. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2098. new_param, conv_bias_opr.execution_policy(),
  2099. conv_bias_opr.config());
  2100. } else {
  2101. new_conv_bias_opr = opr::ConvBias::make(
  2102. conv_bias_src, conv_bias_filter, new_param,
  2103. conv_bias_opr.execution_policy(),
  2104. conv_bias_opr.config());
  2105. }
  2106. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2107. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2108. "The conv_bias dst dim is not trans to nchwxx");
  2109. return new_opr;
  2110. } else {
  2111. mgb_assert(is_trans.first == TransType::TRANS_HYBIRD_NCHWXX);
  2112. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2113. *conv_bias_bias = nullptr;
  2114. auto new_filter =
  2115. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  2116. conv_bias_filter = new_filter.node();
  2117. //! bias trans to nchwxx mode, bias may be scale
  2118. if (new_inp.size() > 2) {
  2119. if (new_inp[2]->shape().ndim == 4) {
  2120. auto new_bias = RelayoutPlaceholder::make(
  2121. new_inp[2], src_to_nchwxx_mode);
  2122. conv_bias_bias = new_bias.node();
  2123. } else {
  2124. mgb_assert(new_inp[2]->shape().ndim == 5);
  2125. conv_bias_bias = new_inp[2];
  2126. }
  2127. }
  2128. mgb_assert(conv_bias_src->shape().ndim == 4 &&
  2129. conv_bias_filter->shape().ndim == 5);
  2130. auto new_param = conv_bias_opr.param();
  2131. new_param.format = conv_bias_format;
  2132. SymbolVar new_conv_bias_opr;
  2133. if (conv_bias_bias) {
  2134. new_conv_bias_opr = opr::ConvBias::make(
  2135. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2136. new_param, conv_bias_opr.execution_policy(),
  2137. conv_bias_opr.config());
  2138. } else {
  2139. new_conv_bias_opr = opr::ConvBias::make(
  2140. conv_bias_src, conv_bias_filter, new_param,
  2141. conv_bias_opr.execution_policy(),
  2142. conv_bias_opr.config());
  2143. }
  2144. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2145. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2146. "The conv dst dim is not trans to nchwxx");
  2147. return new_opr;
  2148. }
  2149. };
  2150. auto replace_pooling_opr = [=](OperatorNodeBase* opr,
  2151. const VarNodeArray& new_inp) {
  2152. mgb_assert(opr->input().size() == new_inp.size());
  2153. auto& pooling_opr = opr->cast_final_safe<opr::PoolingForward>();
  2154. mgb_assert(pooling_opr.param().format ==
  2155. megdnn::param::Pooling::Format::NCHW,
  2156. "ConvertFormat Pass only support converting NCHW to NCHWxx");
  2157. VarNode* inp = new_inp[0];
  2158. //! if input is nchwxx
  2159. if (inp->shape().ndim == 5) {
  2160. auto new_param = pooling_opr.param();
  2161. new_param.format = pooling_format;
  2162. auto new_pooling_opr =
  2163. opr::PoolingForward::make(inp, new_param, opr->config());
  2164. mgb_assert(new_pooling_opr.shape().ndim == 5,
  2165. "The pooling dst dim is not trans to nchwxx");
  2166. return new_pooling_opr.node()->owner_opr();
  2167. } else {
  2168. auto new_opr = serialization::copy_opr_shallow(*opr, new_inp,
  2169. opr->config());
  2170. return new_opr;
  2171. }
  2172. };
  2173. //! When input change and all input can convert to nchwxx, this opr will run
  2174. //! in nchwxx mode, else it will run in nchw mode, for example concat and
  2175. //! elemwise opr
  2176. auto replace_multi_inp_opr = [=](OperatorNodeBase* opr,
  2177. const VarNodeArray& new_inp) {
  2178. mgb_assert(opr->input().size() == new_inp.size());
  2179. bool has_inp_changed = false;
  2180. bool can_exec_ncwxx = true;
  2181. for (size_t i = 0; i < opr->input().size(); i++) {
  2182. if (new_inp[i]->shape().ndim == 5) {
  2183. has_inp_changed = true;
  2184. } else if (new_inp[i]->shape().ndim == 4) {
  2185. if (new_inp[i]->shape()[1] % pack_c_size != 0) {
  2186. can_exec_ncwxx = false;
  2187. }
  2188. } else if (!new_inp[i]->shape().is_scalar()) {
  2189. can_exec_ncwxx = false;
  2190. }
  2191. }
  2192. if (has_inp_changed) {
  2193. auto temp_inp = new_inp;
  2194. if (can_exec_ncwxx) {
  2195. for (size_t i = 0; i < opr->input().size(); i++) {
  2196. if (new_inp[i]->shape().ndim == 4) {
  2197. auto new_var = RelayoutPlaceholder::make(
  2198. new_inp[i], src_to_nchwxx_mode);
  2199. temp_inp[i] = new_var.node();
  2200. } else {
  2201. mgb_assert((new_inp[i]->shape().ndim == 5) ||
  2202. new_inp[i]->shape().is_scalar());
  2203. }
  2204. }
  2205. } else {
  2206. for (size_t i = 0; i < opr->input().size(); i++) {
  2207. if (new_inp[i]->shape().ndim == 5) {
  2208. auto new_var = RelayoutPlaceholder::make(
  2209. new_inp[i], src_to_nchw_mode);
  2210. temp_inp[i] = new_var.node();
  2211. }
  2212. }
  2213. }
  2214. return serialization::copy_opr_shallow(*opr, temp_inp,
  2215. opr->config());
  2216. } else {
  2217. return serialization::copy_opr_shallow(*opr, new_inp,
  2218. opr->config());
  2219. }
  2220. };
  2221. auto relayout_inp_to_nchw = [=](OperatorNodeBase* opr,
  2222. const VarNodeArray& new_inp) {
  2223. mgb_assert(opr->input().size() == new_inp.size());
  2224. VarNodeArray temp_inp = new_inp;
  2225. for (size_t i = 0; i < opr->input().size(); i++) {
  2226. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  2227. mgb_assert(opr->input(i)->shape().ndim == 4);
  2228. mgb_assert(new_inp[i]->shape().ndim == 5);
  2229. auto new_var =
  2230. RelayoutPlaceholder::make(new_inp[i], src_to_nchw_mode);
  2231. temp_inp[i] = new_var.node();
  2232. }
  2233. }
  2234. return serialization::copy_opr_shallow(*opr, temp_inp, opr->config());
  2235. };
  2236. auto&& replace_func = m_opr_replace_func;
  2237. //! supportted nchwxx
  2238. replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
  2239. replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
  2240. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  2241. replace_func[opr::Concat::typeinfo()] = replace_multi_inp_opr;
  2242. replace_func[opr::Elemwise::typeinfo()] = replace_multi_inp_opr;
  2243. replace_func[opr::TypeCvt::typeinfo()] = replace_multi_inp_opr;
  2244. replace_func[opr::ElemwiseMultiType::typeinfo()] = replace_multi_inp_opr;
  2245. replace_func[opr::PowC::typeinfo()] = replace_multi_inp_opr;
  2246. //! not support yet
  2247. replace_func[opr::ConvolutionBackwardData::typeinfo()] =
  2248. relayout_inp_to_nchw;
  2249. replace_func[opr::Subtensor::typeinfo()] = relayout_inp_to_nchw;
  2250. replace_func[opr::GetVarShape::typeinfo()] = relayout_inp_to_nchw;
  2251. replace_func[opr::Dimshuffle::typeinfo()] = relayout_inp_to_nchw;
  2252. replace_func[opr::Reduce::typeinfo()] = relayout_inp_to_nchw;
  2253. replace_func[opr::AssertEqual::typeinfo()] = relayout_inp_to_nchw;
  2254. replace_func[opr::IncrSubtensor::typeinfo()] = relayout_inp_to_nchw;
  2255. replace_func[opr::ResizeForward::typeinfo()] = relayout_inp_to_nchw;
  2256. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  2257. relayout_inp_to_nchw;
  2258. replace_func[opr::WarpAffineForward::typeinfo()] = relayout_inp_to_nchw;
  2259. replace_func[opr::Reshape::typeinfo()] = relayout_inp_to_nchw;
  2260. replace_func[opr::AxisAddRemove::typeinfo()] = relayout_inp_to_nchw;
  2261. replace_func[opr::Argmax::typeinfo()] = relayout_inp_to_nchw;
  2262. replace_func[opr::Broadcast::typeinfo()] = relayout_inp_to_nchw;
  2263. replace_func[opr::ImmutableTensor::typeinfo()] = relayout_inp_to_nchw;
  2264. }
  2265. std::unique_ptr<EnableNchwxxPass> EnableNchwxxPass::make_nchwxx_converter(
  2266. size_t pack_c_size) {
  2267. MIDOUT_B("EnableNchwxxPass::make")
  2268. auto ret = std::make_unique<EnableNchwxxPass>(pack_c_size);
  2269. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  2270. std::string convter_pass_name = "conv_format_nchw88";
  2271. if (pack_c_size == 4) {
  2272. convter_pass_name = "conv_format_nchw44";
  2273. }
  2274. ret->fill_opr_convert_fun(pack_c_size);
  2275. ret->set_name(convter_pass_name);
  2276. return ret;
  2277. MIDOUT_E
  2278. }
  2279. /* ================ EnableNchw44DotPass =============== */
  2280. VarNode* EnableNchw44DotPass::on_graph_endpoint_var(VarNode* new_var,
  2281. VarNode* orig_var) const {
  2282. if (!orig_var->shape().eq_shape(new_var->shape())) {
  2283. return RelayoutPlaceholder::make(
  2284. new_var, RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
  2285. .node();
  2286. }
  2287. return new_var;
  2288. }
  2289. std::unique_ptr<EnableNchw44DotPass>
  2290. EnableNchw44DotPass::make_nchw44_dot_converter() {
  2291. MIDOUT_B("EnableNchw44DotPass::make")
  2292. auto ret = std::make_unique<EnableNchw44DotPass>();
  2293. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  2294. //! First is whether the conv can trans to nchwxx, second is the filter
  2295. //! trans mode
  2296. using RelayoutMode = RelayoutPlaceholder::LayoutType;
  2297. struct TestTransResult {
  2298. TransType trans_type;
  2299. RelayoutMode relayout_mod;
  2300. megdnn::param::ConvolutionV0::Format conv_format;
  2301. };
  2302. constexpr size_t pack_c_size = 4_z;
  2303. auto test_trans_nchw44_dot =
  2304. [](const megdnn::param::Convolution::Sparse conv_mode,
  2305. const VarNode* filter, const size_t stride_h,
  2306. const size_t stride_w,
  2307. const bool valid_nchw_nchw44) -> TestTransResult {
  2308. TestTransResult ret{TransType::TRANS_NONE, {}, {}};
  2309. bool is_int8 = filter->dtype().enumv() == DTypeEnum::QuantizedS8 ||
  2310. filter->dtype().enumv() == DTypeEnum::Int8;
  2311. if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
  2312. size_t OC = filter->shape()[0];
  2313. size_t IC = filter->shape()[1];
  2314. if ((IC % pack_c_size == 0) && (OC % pack_c_size == 0)) {
  2315. ret.trans_type = TransType::TRANS_PURE_NCHWXX;
  2316. if (is_int8) {
  2317. ret.relayout_mod =
  2318. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DOT_DENSE;
  2319. ret.conv_format =
  2320. megdnn::param::ConvBias::Format::NCHW44_DOT;
  2321. } else {
  2322. ret.relayout_mod =
  2323. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DENSE;
  2324. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2325. }
  2326. } else if (valid_nchw_nchw44) {
  2327. ret.trans_type = TransType::TRANS_HYBIRD_NCHWXX;
  2328. ret.relayout_mod = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW44;
  2329. if (is_int8) {
  2330. ret.conv_format =
  2331. megdnn::param::ConvBias::Format::NCHW44_DOT;
  2332. } else {
  2333. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2334. }
  2335. }
  2336. } else {
  2337. mgb_assert(conv_mode == megdnn::param::Convolution::Sparse::GROUP);
  2338. size_t group = filter->shape()[0];
  2339. size_t ocpg = filter->shape()[1];
  2340. size_t icpg = filter->shape()[2];
  2341. if (icpg == 1 && ocpg == 1 && (group % pack_c_size == 0)) {
  2342. ret.trans_type = TransType::TRANS_PURE_NCHWXX;
  2343. ret.relayout_mod = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_CHAN;
  2344. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2345. } else if ((icpg % pack_c_size == 0) && (ocpg % pack_c_size == 0)) {
  2346. ret.trans_type = TransType::TRANS_PURE_NCHWXX;
  2347. if (is_int8) {
  2348. ret.relayout_mod =
  2349. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DOT_GROUP;
  2350. ret.conv_format =
  2351. megdnn::param::ConvBias::Format::NCHW44_DOT;
  2352. } else {
  2353. ret.relayout_mod =
  2354. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_GROUP;
  2355. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2356. }
  2357. }
  2358. }
  2359. return ret;
  2360. };
  2361. auto replace_conv_opr = [test_trans_nchw44_dot](
  2362. OperatorNodeBase* opr,
  2363. const VarNodeArray& new_inp) {
  2364. mgb_assert(opr->input().size() == new_inp.size());
  2365. auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
  2366. mgb_assert(conv_opr.param().format ==
  2367. megdnn::param::Convolution::Format::NCHW,
  2368. "ConvertFormat Pass only support converting NCHW to "
  2369. "NCHW44_DOT");
  2370. bool valid_nchw_nchw44 = nchw_nchwxx_valid(
  2371. conv_opr, new_inp, pack_c_size,
  2372. megdnn::param::ConvBias::NonlineMode::IDENTITY, true);
  2373. auto is_trans = test_trans_nchw44_dot(
  2374. conv_opr.param().sparse, new_inp[1], conv_opr.param().stride_h,
  2375. conv_opr.param().stride_w, valid_nchw_nchw44);
  2376. //! can not trans to nchwxx
  2377. if (is_trans.trans_type == TransType::TRANS_NONE) {
  2378. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2379. new_inp[1]->shape().ndim == 5,
  2380. "The origin filter is not NCHW mode");
  2381. VarNodeArray temp_inp = new_inp;
  2382. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  2383. if (temp_inp[0]->shape().ndim == 5) {
  2384. auto new_src = RelayoutPlaceholder::make(
  2385. new_inp[0], RelayoutMode::NCHW4_TO_NCHW);
  2386. temp_inp[0] = new_src.node();
  2387. }
  2388. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  2389. opr->config());
  2390. return new_opr;
  2391. } else if (is_trans.trans_type == TransType::TRANS_PURE_NCHWXX) {
  2392. //! filter trans to nchwxx mode
  2393. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2394. new_inp[1]->shape().ndim == 5,
  2395. "The origin filter is not NCHW mode");
  2396. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  2397. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2398. is_trans.relayout_mod);
  2399. conv_filter = new_filter.node();
  2400. //! src trans to nchwxx mode
  2401. if (new_inp[0]->shape().ndim != 5) {
  2402. mgb_assert(new_inp[0]->shape().ndim == 4);
  2403. auto new_src = RelayoutPlaceholder::make(
  2404. new_inp[0], RelayoutMode::NCHW_TO_NCHW4);
  2405. conv_src = new_src.node();
  2406. }
  2407. auto new_param = conv_opr.param();
  2408. new_param.format = is_trans.conv_format;
  2409. mgb_assert(conv_src->shape().ndim == 5 &&
  2410. conv_filter->shape().ndim >= 6,
  2411. "The conv src dim is not trans to nchwxx");
  2412. auto new_conv_opr = opr::Convolution::make(
  2413. conv_src, conv_filter, new_param,
  2414. conv_opr.execution_policy(), conv_opr.config());
  2415. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  2416. mgb_assert(new_conv_opr.shape().ndim == 5,
  2417. "The conv dst dim is not trans to nchwxx");
  2418. return new_opr;
  2419. } else {
  2420. mgb_assert(is_trans.trans_type == TransType::TRANS_HYBIRD_NCHWXX);
  2421. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  2422. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2423. is_trans.relayout_mod);
  2424. conv_filter = new_filter.node();
  2425. mgb_assert(conv_src->shape().ndim == 4 &&
  2426. conv_filter->shape().ndim == 5,
  2427. "The src and filter is OK");
  2428. auto new_param = conv_opr.param();
  2429. new_param.format = is_trans.conv_format;
  2430. auto new_conv_opr = opr::Convolution::make(
  2431. conv_src, conv_filter, new_param,
  2432. conv_opr.execution_policy(), conv_opr.config());
  2433. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  2434. mgb_assert(new_conv_opr.shape().ndim == 5,
  2435. "The conv dst dim is not trans to nchwxx");
  2436. return new_opr;
  2437. }
  2438. };
  2439. auto replace_conv_bias_opr = [test_trans_nchw44_dot](
  2440. OperatorNodeBase* opr,
  2441. const VarNodeArray& new_inp) {
  2442. mgb_assert(opr->input().size() == new_inp.size());
  2443. mgb_assert(opr->input().size() <= 3,
  2444. "nchwxx-dot does not support conv_bias fuse Z right now");
  2445. auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
  2446. mgb_assert(conv_bias_opr.param().format ==
  2447. megdnn::param::ConvBias::Format::NCHW,
  2448. "ConvertFormat Pass only support converting NCHW to NCHWXX");
  2449. bool valid_nchw_nchw44 =
  2450. nchw_nchwxx_valid(conv_bias_opr, new_inp, pack_c_size,
  2451. conv_bias_opr.param().nonlineMode, true);
  2452. auto is_trans = test_trans_nchw44_dot(
  2453. conv_bias_opr.param().sparse, new_inp[1],
  2454. conv_bias_opr.param().stride_h, conv_bias_opr.param().stride_w,
  2455. valid_nchw_nchw44);
  2456. auto megdnn_conv =
  2457. opr::intl::get_megdnn_handle(conv_bias_opr.comp_node())
  2458. ->create_operator<megdnn::ConvBiasForward>();
  2459. SmallVector<TensorLayout> layouts;
  2460. //! can not trans to nchwxx
  2461. if (is_trans.trans_type == TransType::TRANS_NONE) {
  2462. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2463. new_inp[1]->shape().ndim == 5,
  2464. "The origin filter is not NCHW mode");
  2465. VarNodeArray temp_inp = new_inp;
  2466. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  2467. if (temp_inp[0]->shape().ndim == 5) {
  2468. auto new_src = RelayoutPlaceholder::make(
  2469. new_inp[0], RelayoutMode::NCHW4_TO_NCHW);
  2470. temp_inp[0] = new_src.node();
  2471. }
  2472. //! the bias is nchwxx
  2473. if (new_inp.size() > 2 && temp_inp[2]->shape().ndim == 5) {
  2474. auto new_bias = RelayoutPlaceholder::make(
  2475. new_inp[2], RelayoutMode::NCHW4_TO_NCHW);
  2476. temp_inp[2] = new_bias.node();
  2477. }
  2478. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  2479. opr->config());
  2480. return new_opr;
  2481. } else if (is_trans.trans_type == TransType::TRANS_PURE_NCHWXX) {
  2482. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2483. *conv_bias_bias = nullptr;
  2484. //! filter trans to nchwxx mode
  2485. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2486. new_inp[1]->shape().ndim == 5,
  2487. "The origin filter is not NCHW mode");
  2488. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2489. is_trans.relayout_mod);
  2490. conv_bias_filter = new_filter.node();
  2491. //! src trans to nchwxx mode
  2492. if (new_inp[0]->shape().ndim != 5) {
  2493. mgb_assert(new_inp[0]->shape().ndim == 4);
  2494. auto new_src = RelayoutPlaceholder::make(
  2495. new_inp[0], RelayoutMode::NCHW_TO_NCHW4);
  2496. conv_bias_src = new_src.node();
  2497. }
  2498. //! bias trans to nchwxx mode
  2499. if (new_inp.size() > 2) {
  2500. if (new_inp[2]->shape().ndim == 4) {
  2501. auto new_bias = RelayoutPlaceholder::make(
  2502. new_inp[2], RelayoutMode::NCHW_TO_NCHW4);
  2503. conv_bias_bias = new_bias.node();
  2504. } else {
  2505. mgb_assert(new_inp[2]->shape().ndim == 5);
  2506. conv_bias_bias = new_inp[2];
  2507. }
  2508. }
  2509. auto new_param = conv_bias_opr.param();
  2510. new_param.format = is_trans.conv_format;
  2511. mgb_assert(conv_bias_src->shape().ndim == 5 &&
  2512. conv_bias_filter->shape().ndim >= 6,
  2513. "The conv_bias src dim is not trans to nchwxx");
  2514. SymbolVar new_conv_bias_opr;
  2515. if (conv_bias_bias) {
  2516. new_conv_bias_opr = opr::ConvBias::make(
  2517. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2518. new_param, conv_bias_opr.execution_policy(),
  2519. conv_bias_opr.config());
  2520. } else {
  2521. new_conv_bias_opr = opr::ConvBias::make(
  2522. conv_bias_src, conv_bias_filter, new_param,
  2523. conv_bias_opr.execution_policy(),
  2524. conv_bias_opr.config());
  2525. }
  2526. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2527. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2528. "The conv_bias dst dim is not trans to nchwxx");
  2529. return new_opr;
  2530. } else {
  2531. mgb_assert(is_trans.trans_type == TransType::TRANS_HYBIRD_NCHWXX);
  2532. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2533. *conv_bias_bias = nullptr;
  2534. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2535. is_trans.relayout_mod);
  2536. conv_bias_filter = new_filter.node();
  2537. //! bias trans to nchwxx mode, bias may be scale
  2538. if (new_inp.size() > 2) {
  2539. if (new_inp[2]->shape().ndim == 4) {
  2540. auto new_bias = RelayoutPlaceholder::make(
  2541. new_inp[2], RelayoutMode::NCHW_TO_NCHW4);
  2542. conv_bias_bias = new_bias.node();
  2543. } else {
  2544. mgb_assert(new_inp[2]->shape().ndim == 5);
  2545. conv_bias_bias = new_inp[2];
  2546. }
  2547. }
  2548. mgb_assert(conv_bias_src->shape().ndim == 4 &&
  2549. conv_bias_filter->shape().ndim == 5);
  2550. auto new_param = conv_bias_opr.param();
  2551. new_param.format = is_trans.conv_format;
  2552. SymbolVar new_conv_bias_opr;
  2553. if (conv_bias_bias) {
  2554. new_conv_bias_opr = opr::ConvBias::make(
  2555. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2556. new_param, conv_bias_opr.execution_policy(),
  2557. conv_bias_opr.config());
  2558. } else {
  2559. new_conv_bias_opr = opr::ConvBias::make(
  2560. conv_bias_src, conv_bias_filter, new_param,
  2561. conv_bias_opr.execution_policy(),
  2562. conv_bias_opr.config());
  2563. }
  2564. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2565. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2566. "The conv dst dim is not trans to nchwxx");
  2567. return new_opr;
  2568. }
  2569. };
  2570. ret->fill_opr_convert_fun(4);
  2571. auto&& replace_func = ret->m_opr_replace_func;
  2572. //! supportted nchwxx
  2573. replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
  2574. replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
  2575. return ret;
  2576. MIDOUT_E
  2577. }
  2578. /* ==================== ShuffleShuffleRemovePass ================= */
  2579. class ShuffleShuffleRemovePass::Impl {
  2580. using TensorFormat = opr::ConvBias::Param::Format;
  2581. OptState& m_opt_state;
  2582. ThinHashMap<std::pair<TensorFormat, TensorFormat>,
  2583. thin_function<VarNode*(VarNode*)>>
  2584. m_reformat;
  2585. class AbstractShuffleOpr;
  2586. void detect_shuffle_operations();
  2587. void do_replace();
  2588. public:
  2589. Impl(OptState& opt_state) : m_opt_state{opt_state} {
  2590. m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::NCHW4)] =
  2591. [](VarNode* inp) -> VarNode* {
  2592. auto x = SymbolVar(inp);
  2593. auto xshp = opr::GetVarShape::make(x);
  2594. auto cv = [&x](int v) { return x.make_scalar(v); };
  2595. auto sub = [&xshp, &cv](int idx) {
  2596. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2597. };
  2598. auto tshp = opr::Concat::make(
  2599. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
  2600. auto y0 = opr::Reshape::make(x, tshp);
  2601. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  2602. return y1.node();
  2603. };
  2604. m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::NCHW32)] =
  2605. [](VarNode* inp) -> VarNode* {
  2606. auto x = SymbolVar(inp);
  2607. auto xshp = opr::GetVarShape::make(x);
  2608. auto cv = [&x](int v) { return x.make_scalar(v); };
  2609. auto sub = [&xshp, &cv](int idx) {
  2610. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2611. };
  2612. auto tshp = opr::Concat::make(
  2613. {sub(0), sub(1) / 32, cv(32), sub(2), sub(3)}, 0);
  2614. auto y0 = opr::Reshape::make(x, tshp);
  2615. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  2616. return y1.node();
  2617. };
  2618. m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::NCHW)] =
  2619. [](VarNode* inp) -> VarNode* {
  2620. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  2621. auto x = SymbolVar(inp);
  2622. auto xshp = opr::GetVarShape::make(x);
  2623. auto cv = [&x](int v) { return x.make_scalar(v); };
  2624. auto sub = [&xshp, &cv](int idx) {
  2625. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2626. };
  2627. auto tshp =
  2628. opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
  2629. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  2630. auto y1 = opr::Reshape::make(y0, tshp);
  2631. return y1.node();
  2632. };
  2633. m_reformat[std::make_pair(TensorFormat::NCHW32, TensorFormat::NCHW)] =
  2634. [](VarNode* inp) -> VarNode* {
  2635. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
  2636. auto x = SymbolVar(inp);
  2637. auto xshp = opr::GetVarShape::make(x);
  2638. auto cv = [&x](int v) { return x.make_scalar(v); };
  2639. auto sub = [&xshp, &cv](int idx) {
  2640. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2641. };
  2642. auto tshp =
  2643. opr::Concat::make({sub(0), sub(1) * 32, sub(2), sub(3)}, 0);
  2644. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  2645. auto y1 = opr::Reshape::make(y0, tshp);
  2646. return y1.node();
  2647. };
  2648. m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::NCHW32)] =
  2649. [](VarNode* inp) -> VarNode* {
  2650. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  2651. auto x = SymbolVar(inp);
  2652. auto xshp = opr::GetVarShape::make(x);
  2653. auto cv = [&x](int v) { return x.make_scalar(v); };
  2654. auto sub = [&xshp, &cv](int idx) {
  2655. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2656. };
  2657. auto tshp0 = opr::Concat::make(
  2658. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)},
  2659. 0),
  2660. tshp1 = opr::Concat::make(
  2661. {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
  2662. auto y0 = opr::Reshape::make(x, tshp0);
  2663. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  2664. auto y2 = opr::Reshape::make(y1, tshp1);
  2665. return y2.node();
  2666. };
  2667. m_reformat[std::make_pair(TensorFormat::NCHW32, TensorFormat::NCHW4)] =
  2668. [](VarNode* inp) -> VarNode* {
  2669. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
  2670. auto x = SymbolVar(inp);
  2671. auto xshp = opr::GetVarShape::make(x);
  2672. auto cv = [&x](int v) { return x.make_scalar(v); };
  2673. auto sub = [&xshp, &cv](int idx) {
  2674. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2675. };
  2676. auto tshp0 = opr::Concat::make(
  2677. {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8},
  2678. 0),
  2679. tshp1 = opr::Concat::make(
  2680. {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
  2681. auto y0 = opr::Reshape::make(x, tshp0);
  2682. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  2683. auto y2 = opr::Reshape::make(y1, tshp1);
  2684. return y2.node();
  2685. };
  2686. m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::CHWN4)] =
  2687. [](VarNode* inp) -> VarNode* {
  2688. megdnn::param::RelayoutFormat param;
  2689. param.mode = megdnn::param::RelayoutFormat::Mode::NCHW4_CHWN4;
  2690. auto reformat = opr::RelayoutFormat::make(inp, param);
  2691. return reformat.node();
  2692. };
  2693. m_reformat[std::make_pair(TensorFormat::CHWN4, TensorFormat::NCHW4)] =
  2694. [](VarNode* inp) -> VarNode* {
  2695. megdnn::param::RelayoutFormat param;
  2696. param.mode = megdnn::param::RelayoutFormat::Mode::CHWN4_NCHW4;
  2697. auto reformat = opr::RelayoutFormat::make(inp, param);
  2698. return reformat.node();
  2699. };
  2700. m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::CHWN4)] =
  2701. [](VarNode* inp) -> VarNode* {
  2702. auto x = SymbolVar(inp);
  2703. auto xshp = opr::GetVarShape::make(x);
  2704. auto cv = [&x](int v) { return x.make_scalar(v); };
  2705. auto sub = [&xshp, &cv](int idx) {
  2706. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2707. };
  2708. auto tshp = opr::Concat::make(
  2709. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
  2710. auto y0 = opr::Reshape::make(x, tshp);
  2711. auto y1 = opr::Dimshuffle::make(y0, {1, 3, 4, 0, 2});
  2712. return y1.node();
  2713. };
  2714. m_reformat[std::make_pair(TensorFormat::CHWN4, TensorFormat::NCHW)] =
  2715. [](VarNode* inp) -> VarNode* {
  2716. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  2717. auto x = SymbolVar(inp);
  2718. auto xshp = opr::GetVarShape::make(x);
  2719. auto cv = [&x](int v) { return x.make_scalar(v); };
  2720. auto sub = [&xshp, &cv](int idx) {
  2721. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2722. };
  2723. auto tshp =
  2724. opr::Concat::make({sub(3), sub(0) * 4, sub(1), sub(2)}, 0);
  2725. auto y0 = opr::Dimshuffle::make(x, {3, 0, 4, 1, 2});
  2726. auto y1 = opr::Reshape::make(y0, tshp);
  2727. return y1.node();
  2728. };
  2729. detect_shuffle_operations();
  2730. do_replace();
  2731. }
  2732. };
  2733. /*!
  2734. * \brief abstract operator representation of shuffle operation
  2735. */
  2736. MGB_DEFINE_OPR_CLASS(ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr,
  2737. cg::SingleCNOperatorNodeBase) // {
  2738. public:
  2739. AbstractShuffleOpr(VarNode* inpvar, TensorFormat inp_format,
  2740. TensorFormat out_format);
  2741. static SymbolVar make(VarNode* inpvar, TensorFormat inp_format,
  2742. TensorFormat out_format);
  2743. TensorFormat inp_format() const {
  2744. return m_inp_format;
  2745. }
  2746. TensorFormat out_format() const {
  2747. return m_out_format;
  2748. }
  2749. private:
  2750. void init_output_static_infer_desc() override;
  2751. void scn_do_execute() override;
  2752. const TensorFormat m_inp_format;
  2753. const TensorFormat m_out_format;
  2754. };
  2755. MGB_DYN_TYPE_OBJ_FINAL_IMPL(ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr);
  2756. void ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::scn_do_execute() {
  2757. mgb_throw(InternalError, "AbstractShuffleOpr cannot be executed");
  2758. }
  2759. void ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::
  2760. init_output_static_infer_desc() {
  2761. using namespace cg::static_infer;
  2762. auto&& mgr = owner_graph()->static_infer_manager();
  2763. DepVal deps;
  2764. for (auto i : input())
  2765. deps.push_back({i, DepType::SHAPE});
  2766. auto infer_shape = [this](TensorShape& dst, const InpVal& inp) {
  2767. TensorShape inp_shape = inp.val[0].shape();
  2768. if (m_inp_format == TensorFormat::NCHW4 &&
  2769. m_out_format == TensorFormat::NCHW32) {
  2770. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  2771. dst = inp_shape;
  2772. dst[0] = inp_shape[0];
  2773. dst[1] = inp_shape[1] / 8;
  2774. dst[2] = inp_shape[2];
  2775. dst[3] = inp_shape[3];
  2776. dst[4] = inp_shape[4] * 8;
  2777. } else if (m_inp_format == TensorFormat::NCHW32 &&
  2778. m_out_format == TensorFormat::NCHW4) {
  2779. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
  2780. dst = inp_shape;
  2781. dst[0] = inp_shape[0];
  2782. dst[1] = inp_shape[1] * 8;
  2783. dst[2] = inp_shape[2];
  2784. dst[3] = inp_shape[3];
  2785. dst[4] = inp_shape[4] / 8;
  2786. } else if (m_inp_format == TensorFormat::NCHW &&
  2787. m_out_format == TensorFormat::NCHW4) {
  2788. mgb_assert(inp_shape.ndim == 4);
  2789. dst.ndim = 5;
  2790. dst[0] = inp_shape[0];
  2791. dst[1] = inp_shape[1] / 4;
  2792. dst[2] = inp_shape[2];
  2793. dst[3] = inp_shape[3];
  2794. dst[4] = 4;
  2795. } else if (m_inp_format == TensorFormat::NCHW4 &&
  2796. m_out_format == TensorFormat::NCHW) {
  2797. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  2798. dst.ndim = 4;
  2799. dst[0] = inp_shape[0];
  2800. dst[1] = inp_shape[1] * 4;
  2801. dst[2] = inp_shape[2];
  2802. dst[3] = inp_shape[3];
  2803. } else if (m_inp_format == TensorFormat::NCHW4 &&
  2804. m_out_format == TensorFormat::CHWN4) {
  2805. dst.ndim = 5;
  2806. dst[0] = inp_shape[1];
  2807. dst[1] = inp_shape[2];
  2808. dst[2] = inp_shape[3];
  2809. dst[3] = inp_shape[0];
  2810. dst[4] = inp_shape[4];
  2811. } else if (m_inp_format == TensorFormat::CHWN4 &&
  2812. m_out_format == TensorFormat::NCHW4) {
  2813. dst.ndim = 5;
  2814. dst[0] = inp_shape[3];
  2815. dst[1] = inp_shape[0];
  2816. dst[2] = inp_shape[1];
  2817. dst[3] = inp_shape[2];
  2818. dst[4] = inp_shape[4];
  2819. } else {
  2820. mgb_throw(InternalError,
  2821. "Unsupported input format and output format.");
  2822. }
  2823. return true;
  2824. };
  2825. mgr.register_shape_infer(output(0), {SourceType::DEP, deps, infer_shape});
  2826. }
  2827. ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::AbstractShuffleOpr(
  2828. VarNode* inpvar, TensorFormat inp_format, TensorFormat out_format)
  2829. : Super(inpvar->owner_graph(), {}, "AbstractShuffleOpr", {inpvar}),
  2830. m_inp_format{inp_format},
  2831. m_out_format{out_format} {
  2832. add_input({inpvar});
  2833. add_equivalence_component<ScalarHash<TensorFormat>>(m_inp_format);
  2834. add_equivalence_component<ScalarHash<TensorFormat>>(m_out_format);
  2835. add_output(None)->dtype(inpvar->dtype());
  2836. }
  2837. SymbolVar ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::make(
  2838. VarNode* inpvar, TensorFormat inp_format, TensorFormat out_format) {
  2839. return inpvar->owner_graph()
  2840. ->insert_opr(std::make_unique<AbstractShuffleOpr>(
  2841. inpvar, inp_format, out_format))
  2842. ->output(0);
  2843. }
  2844. void ShuffleShuffleRemovePass::Impl::detect_shuffle_operations() {
  2845. auto rewriter = m_opt_state.graph().make_rewriter();
  2846. auto uniq_reader_check = UniqReaderCheck{m_opt_state.graph()};
  2847. auto try_reshape_shuffle = [&rewriter,
  2848. &uniq_reader_check](OperatorNodeBase* opr) {
  2849. // check shuffle
  2850. auto shuffle = try_cast_as_op<opr::Dimshuffle>(opr);
  2851. if (shuffle == nullptr)
  2852. return false;
  2853. auto&& param = shuffle->param();
  2854. if (param.pattern_len != 5)
  2855. return false;
  2856. bool is_nchw2nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  2857. param.pattern[2] == 3 && param.pattern[3] == 4 &&
  2858. param.pattern[4] == 2 &&
  2859. opr->output(0)->shape()[4] == 4;
  2860. if (!is_nchw2nchw4)
  2861. return false;
  2862. if (!uniq_reader_check(shuffle->input(0)))
  2863. return false;
  2864. // check reshape
  2865. auto reshape = try_cast_as_op<opr::Reshape>(opr->input(0)->owner_opr());
  2866. if (reshape == nullptr)
  2867. return false;
  2868. auto inp_var = rewriter.get_var(reshape->input(0));
  2869. auto abstract_shuffle = AbstractShuffleOpr::make(
  2870. inp_var, TensorFormat::NCHW, TensorFormat::NCHW4);
  2871. rewriter.replace_var(
  2872. opr->output(0), abstract_shuffle.node(),
  2873. mgb_cstr_log("replace reformat(nchw -> nchw4) to "
  2874. "AbstractShuffleOpr(nchw -> nchw4)."));
  2875. return true;
  2876. };
  2877. auto try_reshape_shuffle_reshape = [&rewriter, &uniq_reader_check](
  2878. OperatorNodeBase* opr) {
  2879. // check reshape
  2880. auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
  2881. if (reshape1 == nullptr)
  2882. return false;
  2883. if (!uniq_reader_check(reshape1->input(0)))
  2884. return false;
  2885. // check shuffle
  2886. auto shuffle =
  2887. try_cast_as_op<opr::Dimshuffle>(opr->input(0)->owner_opr());
  2888. if (shuffle == nullptr)
  2889. return false;
  2890. auto&& param = shuffle->param();
  2891. if (param.pattern_len != 6)
  2892. return false;
  2893. bool is_nchw42nchw32 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  2894. param.pattern[2] == 3 && param.pattern[3] == 4 &&
  2895. param.pattern[4] == 2 && param.pattern[5] == 5 &&
  2896. shuffle->input(0)->shape()[5] == 4 &&
  2897. shuffle->input(0)->shape()[2] == 8;
  2898. bool is_nchw322nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  2899. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  2900. param.pattern[4] == 3 && param.pattern[5] == 5 &&
  2901. shuffle->input(0)->shape()[4] == 8 &&
  2902. shuffle->input(0)->shape()[5] == 4;
  2903. if (!is_nchw42nchw32 && !is_nchw322nchw4)
  2904. return false;
  2905. if (!uniq_reader_check(shuffle->input(0)))
  2906. return false;
  2907. // check reshape
  2908. auto reshape2 =
  2909. try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
  2910. if (reshape2 == nullptr)
  2911. return false;
  2912. auto inp_var = rewriter.get_var(reshape2->input(0));
  2913. TensorFormat inp_format = is_nchw42nchw32 ? TensorFormat::NCHW4
  2914. : TensorFormat::NCHW32,
  2915. out_format = is_nchw42nchw32 ? TensorFormat::NCHW32
  2916. : TensorFormat::NCHW4;
  2917. auto abstract_shuffle =
  2918. AbstractShuffleOpr::make(inp_var, inp_format, out_format);
  2919. std::string reformat_type =
  2920. is_nchw42nchw32 ? "nchw4 -> nchw32" : "nchw32 -> nchw4";
  2921. rewriter.replace_var(opr->output(0), abstract_shuffle.node(),
  2922. mgb_cstr_log(ssprintf("replace reformat(%s) to "
  2923. "AbstractShuffleOpr(%s).",
  2924. reformat_type.c_str(),
  2925. reformat_type.c_str())
  2926. .c_str()));
  2927. return true;
  2928. };
  2929. auto try_shuffle_reshape = [&rewriter,
  2930. &uniq_reader_check](OperatorNodeBase* opr) {
  2931. // check reshape
  2932. auto reshape = try_cast_as_op<opr::Reshape>(opr);
  2933. if (reshape == nullptr)
  2934. return false;
  2935. if (!uniq_reader_check(reshape->input(0)))
  2936. return false;
  2937. // check shuffle
  2938. auto shuffle =
  2939. try_cast_as_op<opr::Dimshuffle>(opr->input(0)->owner_opr());
  2940. if (shuffle == nullptr)
  2941. return false;
  2942. auto&& param = shuffle->param();
  2943. if (param.pattern_len != 5)
  2944. return false;
  2945. bool is_nchw42nchw = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  2946. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  2947. param.pattern[4] == 3 &&
  2948. shuffle->input(0)->shape()[4] == 4;
  2949. if (!is_nchw42nchw)
  2950. return false;
  2951. auto inp_var = rewriter.get_var(shuffle->input(0));
  2952. auto abstract_shuffle = AbstractShuffleOpr::make(
  2953. inp_var, TensorFormat::NCHW4, TensorFormat::NCHW);
  2954. rewriter.replace_var(
  2955. opr->output(0), abstract_shuffle.node(),
  2956. mgb_cstr_log("replace reformat(nchw4 -> nchw) to "
  2957. "AbstractShuffleOpr(nchw4 -> nchw)."));
  2958. return true;
  2959. };
  2960. auto try_relayout_format = [&rewriter](OperatorNodeBase* opr) {
  2961. // check relayout format
  2962. auto reformat = try_cast_as_op<opr::RelayoutFormat>(opr);
  2963. if (reformat == nullptr)
  2964. return false;
  2965. auto&& param = reformat->param();
  2966. if (param.mode != opr::RelayoutFormat::Param::Mode::CHWN4_NCHW4 &&
  2967. param.mode != opr::RelayoutFormat::Param::Mode::NCHW4_CHWN4)
  2968. return false;
  2969. auto inp_var = rewriter.get_var(reformat->input(0));
  2970. cg::SymbolVar abstract_shuffle;
  2971. if (param.mode == opr::RelayoutFormat::Param::Mode::NCHW4_CHWN4) {
  2972. abstract_shuffle = AbstractShuffleOpr::make(
  2973. inp_var, TensorFormat::NCHW4, TensorFormat::CHWN4);
  2974. } else {
  2975. abstract_shuffle = AbstractShuffleOpr::make(
  2976. inp_var, TensorFormat::CHWN4, TensorFormat::NCHW4);
  2977. }
  2978. rewriter.replace_var(
  2979. opr->output(0), abstract_shuffle.node(),
  2980. mgb_cstr_log("replace reformat(nchw4 -> nchw) to "
  2981. "AbstractShuffleOpr(nchw4 -> nchw)."));
  2982. return true;
  2983. };
  2984. auto on_opr = [&try_reshape_shuffle, &try_shuffle_reshape,
  2985. &try_reshape_shuffle_reshape, &try_relayout_format,
  2986. &rewriter, &uniq_reader_check](OperatorNodeBase* opr) {
  2987. if (!try_reshape_shuffle_reshape(opr) && !try_reshape_shuffle(opr) &&
  2988. !try_shuffle_reshape(opr) && !try_relayout_format(opr)) {
  2989. auto new_opr = rewriter.auto_replace_outputs(opr);
  2990. uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
  2991. }
  2992. };
  2993. m_opt_state.graph().iter(on_opr);
  2994. rewriter.apply_inplace();
  2995. }
  2996. void ShuffleShuffleRemovePass::Impl::do_replace() {
  2997. auto rewriter = m_opt_state.graph().make_rewriter();
  2998. auto uniq_reader_check = UniqReaderCheck{m_opt_state.graph()};
  2999. ThinHashMap<VarNode*, VarNode*> var2endpoint;
  3000. ThinHashSet<VarNode*> trt_opr_inps;
  3001. SmallVector<OperatorNodeBase*> topo_order;
  3002. auto cb = [&topo_order, &trt_opr_inps](OperatorNodeBase* opr) {
  3003. topo_order.push_back(opr);
  3004. MGB_MARK_USED_VAR(trt_opr_inps);
  3005. #if MGB_ENABLE_TENSOR_RT
  3006. if (opr->same_type<opr::TensorRTOpr>()) {
  3007. for (auto&& inp : opr->input())
  3008. trt_opr_inps.insert(inp);
  3009. }
  3010. #endif
  3011. };
  3012. m_opt_state.graph().iter(cb);
  3013. for (auto&& opr : reverse_adaptor(topo_order)) {
  3014. if (opr->same_type<opr::TypeCvt>() ||
  3015. opr->same_type<AbstractShuffleOpr>()) {
  3016. auto find = var2endpoint.find(opr->output(0));
  3017. if (find != var2endpoint.end()) {
  3018. if (uniq_reader_check(opr->output(0))) {
  3019. var2endpoint[opr->input(0)] = find->second;
  3020. } else {
  3021. var2endpoint[opr->input(0)] = opr->output(0);
  3022. }
  3023. } else {
  3024. var2endpoint[opr->input(0)] = opr->output(0);
  3025. }
  3026. }
  3027. }
  3028. auto on_opr = [this, &rewriter, &uniq_reader_check, &trt_opr_inps,
  3029. &var2endpoint](OperatorNodeBase* opr) {
  3030. MGB_MARK_USED_VAR(trt_opr_inps);
  3031. bool cond_opr = opr->same_type<opr::TypeCvt>() ||
  3032. opr->same_type<AbstractShuffleOpr>();
  3033. if (cond_opr) {
  3034. bool cond_endpoint = var2endpoint[opr->input(0)] == opr->output(0);
  3035. if (!cond_endpoint)
  3036. return;
  3037. auto cur = opr;
  3038. auto var = opr->output(0), inp_var = opr->input(0);
  3039. bool force_folding_typecvt = false;
  3040. bool first_shuffle = false;
  3041. // initialize inp_format and out_format
  3042. TensorFormat out_format = TensorFormat::NCHW,
  3043. inp_format = out_format;
  3044. megdnn::DType inp_dtype = cur->input(0)->dtype(),
  3045. out_dtype = cur->output(0)->dtype();
  3046. SmallVector<megdnn::DType> out_dtype_vec;
  3047. while (cond_opr) {
  3048. if (cur->same_type<AbstractShuffleOpr>()) {
  3049. auto shuffle = try_cast_as_op<AbstractShuffleOpr>(cur);
  3050. inp_format = shuffle->inp_format();
  3051. if (!first_shuffle) {
  3052. out_format = shuffle->out_format();
  3053. first_shuffle = true;
  3054. }
  3055. } else {
  3056. mgb_assert(cur->same_type<opr::TypeCvt>());
  3057. out_dtype_vec.push_back(cur->output(0)->dtype());
  3058. }
  3059. inp_var = cur->input(0);
  3060. bool cond_reader = uniq_reader_check(inp_var);
  3061. if (!cond_reader)
  3062. break;
  3063. cur = cur->input(0)->owner_opr();
  3064. cond_opr = cur->same_type<opr::TypeCvt>() ||
  3065. cur->same_type<AbstractShuffleOpr>();
  3066. }
  3067. std::reverse(out_dtype_vec.begin(), out_dtype_vec.end());
  3068. #if MGB_ENABLE_TENSOR_RT
  3069. force_folding_typecvt =
  3070. inp_var->owner_opr()->same_type<opr::TensorRTOpr>() ||
  3071. trt_opr_inps.count(var);
  3072. #endif
  3073. auto new_var = rewriter.get_var(inp_var);
  3074. if (inp_format != out_format) {
  3075. mgb_assert(m_reformat.find(std::make_pair(
  3076. inp_format, out_format)) != m_reformat.end(),
  3077. "Unsupported shuffle shuffle remove pass");
  3078. new_var = m_reformat[std::make_pair(inp_format, out_format)](
  3079. new_var);
  3080. }
  3081. if (force_folding_typecvt) {
  3082. inp_dtype = inp_var->dtype();
  3083. if (inp_dtype != out_dtype) {
  3084. auto type_cvt = opr::TypeCvt::make(new_var, out_dtype);
  3085. new_var = type_cvt.node();
  3086. }
  3087. } else {
  3088. if (out_dtype_vec.back() != var->dtype())
  3089. out_dtype_vec.push_back(var->dtype());
  3090. for (auto&& dtype : out_dtype_vec) {
  3091. auto type_cvt = opr::TypeCvt::make(new_var, dtype);
  3092. new_var = type_cvt.node();
  3093. }
  3094. }
  3095. rewriter.replace_var(
  3096. var, new_var,
  3097. mgb_cstr_log("replace Dimshuffle and TypeCvt chain"));
  3098. } else {
  3099. auto new_opr = rewriter.auto_replace_outputs(opr);
  3100. uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
  3101. }
  3102. };
  3103. m_opt_state.graph().iter(on_opr);
  3104. rewriter.apply_inplace();
  3105. }
  3106. const char* ShuffleShuffleRemovePass::name() const {
  3107. return mgb_cstr_log("shuffle shuffle remove pass");
  3108. }
  3109. void ShuffleShuffleRemovePass::apply(OptState& opt) const {
  3110. MIDOUT_B("ShuffleShuffleRemovePass::apply")
  3111. opt.set_var_replace_check_flag(VarReplaceCheckFlag::CHECK_SHAPE |
  3112. VarReplaceCheckFlag::CHECK_DTYPE);
  3113. Impl{opt};
  3114. MIDOUT_E
  3115. }
  3116. /* ==================== FoldingConvBiasDimshufflePass ================= */
  3117. const char* FoldingConvBiasDimshufflePass::name() const {
  3118. return mgb_cstr_log("folding conv bias dimshuffle pass");
  3119. }
  3120. void FoldingConvBiasDimshufflePass::apply(OptState& opt) const {
  3121. MIDOUT_B("FoldingConvBiasDimshufflePass::apply");
  3122. using DepType = cg::OperatorNodeProp::DepType;
  3123. ThinHashMap<OperatorNodeBase*,
  3124. SmallVector<std::pair<OperatorNodeBase*, DepType>>>
  3125. readers;
  3126. static const ThinHashSet<Typeinfo*> opr_type_list = {
  3127. opr::TypeCvt::typeinfo(), opr::Dimshuffle::typeinfo(),
  3128. opr::Reshape::typeinfo(), opr::ConvBias::typeinfo()};
  3129. opt.graph().iter([&readers](OperatorNodeBase* opr) {
  3130. for (auto&& i : opr->node_prop().dep_map()) {
  3131. if (opr_type_list.count(i.first->owner_opr()->dyn_typeinfo())) {
  3132. readers[i.first->owner_opr()].emplace_back(opr, i.second);
  3133. }
  3134. }
  3135. });
  3136. auto rewriter = opt.graph().make_rewriter();
  3137. auto nchw42nchw = [](VarNode* inp) -> VarNode* {
  3138. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  3139. auto x = SymbolVar(inp);
  3140. auto xshp = opr::GetVarShape::make(x);
  3141. auto cv = [&x](int v) { return x.make_scalar(v); };
  3142. auto sub = [&xshp, &cv](int idx) {
  3143. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  3144. };
  3145. auto tshp = opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
  3146. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  3147. auto y1 = opr::Reshape::make(y0, tshp);
  3148. auto y2 = opr::TypeCvt::make(y1, dtype::Float32());
  3149. return y2.node();
  3150. };
  3151. auto nchw42nchw32 = [](VarNode* inp) -> VarNode* {
  3152. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  3153. auto x = SymbolVar(inp);
  3154. auto xshp = opr::GetVarShape::make(x);
  3155. auto cv = [&x](int v) { return x.make_scalar(v); };
  3156. auto sub = [&xshp, &cv](int idx) {
  3157. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  3158. };
  3159. auto tshp0 = opr::Concat::make(
  3160. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)}, 0),
  3161. tshp1 = opr::Concat::make(
  3162. {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
  3163. auto y0 = opr::Reshape::make(x, tshp0);
  3164. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  3165. auto y2 = opr::Reshape::make(y1, tshp1);
  3166. return y2.node();
  3167. };
  3168. auto nchw322nchw4 = [](VarNode* inp) -> VarNode* {
  3169. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
  3170. auto x = SymbolVar(inp);
  3171. auto xshp = opr::GetVarShape::make(x);
  3172. auto cv = [&x](int v) { return x.make_scalar(v); };
  3173. auto sub = [&xshp, &cv](int idx) {
  3174. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  3175. };
  3176. auto tshp0 = opr::Concat::make(
  3177. {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8}, 0),
  3178. tshp1 = opr::Concat::make(
  3179. {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
  3180. auto y0 = opr::Reshape::make(x, tshp0);
  3181. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  3182. auto y2 = opr::Reshape::make(y1, tshp1);
  3183. return y2.node();
  3184. };
  3185. auto try_conv_dimshuffle_reshape_typecvt = [&rewriter, &readers,
  3186. &nchw42nchw](
  3187. OperatorNodeBase* opr) {
  3188. ThinHashSet<OperatorNodeBase*> opr_set;
  3189. ThinHashSet<OperatorNodeBase*> reader_set;
  3190. // check typecvt
  3191. auto typecvt = try_cast_as_op<opr::TypeCvt>(opr);
  3192. if (typecvt == nullptr)
  3193. return false;
  3194. auto inp_dtype = typecvt->input(0)->dtype(),
  3195. out_dtype = typecvt->output(0)->dtype();
  3196. bool is_s82f32 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3197. out_dtype.enumv() == DTypeEnum::Float32;
  3198. if (!is_s82f32)
  3199. return false;
  3200. opr_set.insert(opr);
  3201. // check reshape
  3202. auto reshape =
  3203. try_cast_as_op<opr::Reshape>(typecvt->input(0)->owner_opr());
  3204. if (reshape == nullptr)
  3205. return false;
  3206. opr_set.insert(reshape);
  3207. for (auto&& i : readers[reshape]) {
  3208. if (i.second & DepType::DEV_VALUE) {
  3209. reader_set.insert(i.first);
  3210. }
  3211. }
  3212. // check shuffle
  3213. auto shuffle =
  3214. try_cast_as_op<opr::Dimshuffle>(reshape->input(0)->owner_opr());
  3215. if (shuffle == nullptr)
  3216. return false;
  3217. auto&& param = shuffle->param();
  3218. if (param.pattern_len != 5)
  3219. return false;
  3220. bool is_nchw42nchw = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3221. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  3222. param.pattern[4] == 3 &&
  3223. shuffle->input(0)->shape()[4] == 4;
  3224. if (!is_nchw42nchw)
  3225. return false;
  3226. opr_set.insert(shuffle);
  3227. for (auto&& i : readers[shuffle]) {
  3228. if (i.second & DepType::DEV_VALUE) {
  3229. reader_set.insert(i.first);
  3230. }
  3231. }
  3232. // check conv bias
  3233. auto conv_bias =
  3234. try_cast_as_op<opr::ConvBias>(shuffle->input(0)->owner_opr());
  3235. if (conv_bias == nullptr)
  3236. return false;
  3237. inp_dtype = conv_bias->input(0)->dtype();
  3238. bool is_s8nchw4 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3239. conv_bias->param().format ==
  3240. megdnn::param::ConvBias::Format::NCHW4;
  3241. if (!is_s8nchw4)
  3242. return false;
  3243. if (conv_bias->input().size() != 3)
  3244. return false;
  3245. opr_set.insert(conv_bias);
  3246. for (auto&& i : readers[conv_bias]) {
  3247. if (i.second & DepType::DEV_VALUE) {
  3248. reader_set.insert(i.first);
  3249. }
  3250. }
  3251. for (auto reader : reader_set) {
  3252. if (opr_set.count(reader) <= 0) {
  3253. return false;
  3254. }
  3255. }
  3256. auto src = rewriter.get_var(conv_bias->input(0)),
  3257. filter = rewriter.get_var(conv_bias->input(1)),
  3258. bias = rewriter.get_var(conv_bias->input(2));
  3259. auto new_bias = nchw42nchw(bias);
  3260. auto new_param = conv_bias->param();
  3261. new_param.format = megdnn::param::ConvBias::Format::NCHW4_NCHW;
  3262. auto conv_bias_shuffle = opr::ConvBias::make(
  3263. src, filter, new_bias, new_param, conv_bias->execution_policy(),
  3264. OperatorNodeConfig{dtype::Float32()});
  3265. rewriter.replace_var(opr->output(0), conv_bias_shuffle.node(),
  3266. mgb_cstr_log("replace conv_bias + typecvt + "
  3267. "dimshuffle + "
  3268. "reshape to conv_bias(NCHW4_NCHW)"));
  3269. return true;
  3270. };
  3271. auto try_conv_reformat_nchw42nchw32 = [&rewriter, &nchw42nchw32,
  3272. &readers](OperatorNodeBase* opr) {
  3273. ThinHashSet<OperatorNodeBase*> opr_set;
  3274. ThinHashSet<OperatorNodeBase*> reader_set;
  3275. // check reshape
  3276. auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
  3277. if (reshape1 == nullptr)
  3278. return false;
  3279. opr_set.insert(opr);
  3280. // check dimshuffle
  3281. auto shuffle = try_cast_as_op<opr::Dimshuffle>(
  3282. reshape1->input(0)->owner_opr());
  3283. if (shuffle == nullptr)
  3284. return false;
  3285. auto&& param = shuffle->param();
  3286. if (param.pattern_len != 6)
  3287. return false;
  3288. bool is_nchw42nchw32 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3289. param.pattern[2] == 3 && param.pattern[3] == 4 &&
  3290. param.pattern[4] == 2 && param.pattern[5] == 5 &&
  3291. shuffle->output(0)->shape()[5] == 4 &&
  3292. shuffle->output(0)->shape()[4] == 8;
  3293. if (!is_nchw42nchw32)
  3294. return false;
  3295. opr_set.insert(shuffle);
  3296. for (auto&& i : readers[shuffle]) {
  3297. if (i.second & DepType::DEV_VALUE) {
  3298. reader_set.insert(i.first);
  3299. }
  3300. }
  3301. // check reshape
  3302. auto reshape2 =
  3303. try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
  3304. if (reshape2 == nullptr)
  3305. return false;
  3306. opr_set.insert(reshape2);
  3307. for (auto&& i : readers[reshape2]) {
  3308. if (i.second & DepType::DEV_VALUE) {
  3309. reader_set.insert(i.first);
  3310. }
  3311. }
  3312. // check conv bias
  3313. auto conv_bias =
  3314. try_cast_as_op<opr::ConvBias>(reshape2->input(0)->owner_opr());
  3315. if (conv_bias == nullptr)
  3316. return false;
  3317. auto inp_dtype = conv_bias->input(0)->dtype();
  3318. bool is_s8nchw4 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3319. conv_bias->param().format ==
  3320. megdnn::param::ConvBias::Format::NCHW4;
  3321. if (!is_s8nchw4)
  3322. return false;
  3323. if (conv_bias->input().size() != 3)
  3324. return false;
  3325. opr_set.insert(conv_bias);
  3326. for (auto&& i : readers[conv_bias]) {
  3327. if (i.second & DepType::DEV_VALUE) {
  3328. reader_set.insert(i.first);
  3329. }
  3330. }
  3331. for (auto reader : reader_set) {
  3332. if (opr_set.count(reader) <= 0) {
  3333. return false;
  3334. }
  3335. }
  3336. auto src = rewriter.get_var(conv_bias->input(0)),
  3337. filter = rewriter.get_var(conv_bias->input(1)),
  3338. bias = rewriter.get_var(conv_bias->input(2));
  3339. auto new_bias = nchw42nchw32(bias);
  3340. auto new_param = conv_bias->param();
  3341. new_param.format = megdnn::param::ConvBias::Format::NCHW4_NCHW32;
  3342. auto conv_bias_shuffle = opr::ConvBias::make(
  3343. src, filter, new_bias, new_param, conv_bias->execution_policy(),
  3344. conv_bias->config());
  3345. rewriter.replace_var(
  3346. opr->output(0), conv_bias_shuffle.node(),
  3347. mgb_cstr_log("replace conv_bias + "
  3348. "reformat to conv_bias(NCHW4_NCHW32)"));
  3349. return true;
  3350. };
  3351. auto try_conv_reformat_nchw322nchw4 = [&rewriter, &readers, &nchw322nchw4](
  3352. OperatorNodeBase* opr) {
  3353. ThinHashSet<OperatorNodeBase*> opr_set;
  3354. ThinHashSet<OperatorNodeBase*> reader_set;
  3355. // check reshape
  3356. auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
  3357. if (reshape1 == nullptr)
  3358. return false;
  3359. opr_set.insert(opr);
  3360. // check dimshuffle
  3361. auto shuffle = try_cast_as_op<opr::Dimshuffle>(
  3362. reshape1->input(0)->owner_opr());
  3363. if (shuffle == nullptr)
  3364. return false;
  3365. auto&& param = shuffle->param();
  3366. if (param.pattern_len != 6)
  3367. return false;
  3368. bool is_nchw322nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3369. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  3370. param.pattern[4] == 3 && param.pattern[5] == 5 &&
  3371. shuffle->input(0)->shape()[5] == 4 &&
  3372. shuffle->input(0)->shape()[4] == 8;
  3373. if (!is_nchw322nchw4)
  3374. return false;
  3375. opr_set.insert(shuffle);
  3376. for (auto&& i : readers[shuffle]) {
  3377. if (i.second & DepType::DEV_VALUE) {
  3378. reader_set.insert(i.first);
  3379. }
  3380. }
  3381. // check reshape
  3382. auto reshape2 =
  3383. try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
  3384. if (reshape2 == nullptr)
  3385. return false;
  3386. opr_set.insert(reshape2);
  3387. for (auto&& i : readers[reshape2]) {
  3388. if (i.second & DepType::DEV_VALUE) {
  3389. reader_set.insert(i.first);
  3390. }
  3391. }
  3392. // check conv bias
  3393. auto conv_bias =
  3394. try_cast_as_op<opr::ConvBias>(reshape2->input(0)->owner_opr());
  3395. if (conv_bias == nullptr)
  3396. return false;
  3397. auto inp_dtype = conv_bias->input(0)->dtype();
  3398. bool is_s8nchw32 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3399. conv_bias->param().format ==
  3400. megdnn::param::ConvBias::Format::NCHW32;
  3401. if (!is_s8nchw32)
  3402. return false;
  3403. if (conv_bias->input().size() != 3)
  3404. return false;
  3405. opr_set.insert(conv_bias);
  3406. for (auto&& i : readers[conv_bias]) {
  3407. if (i.second & DepType::DEV_VALUE) {
  3408. reader_set.insert(i.first);
  3409. }
  3410. }
  3411. for (auto reader : reader_set) {
  3412. if (opr_set.count(reader) <= 0) {
  3413. return false;
  3414. }
  3415. }
  3416. auto src = rewriter.get_var(conv_bias->input(0)),
  3417. filter = rewriter.get_var(conv_bias->input(1)),
  3418. bias = rewriter.get_var(conv_bias->input(2));
  3419. auto new_bias = nchw322nchw4(bias);
  3420. auto new_param = conv_bias->param();
  3421. new_param.format = megdnn::param::ConvBias::Format::NCHW32_NCHW4;
  3422. auto conv_bias_shuffle = opr::ConvBias::make(
  3423. src, filter, new_bias, new_param, conv_bias->execution_policy(),
  3424. conv_bias->config());
  3425. rewriter.replace_var(
  3426. opr->output(0), conv_bias_shuffle.node(),
  3427. mgb_cstr_log("replace conv_bias + "
  3428. "reformat to conv_bias(NCHW32_NCHW4)"));
  3429. return true;
  3430. };
  3431. MGB_MARK_USED_VAR(try_conv_reformat_nchw322nchw4);
  3432. auto on_opr = [&try_conv_dimshuffle_reshape_typecvt,
  3433. &try_conv_reformat_nchw42nchw32,
  3434. #if CUDA_VERSION >= 10020
  3435. &try_conv_reformat_nchw322nchw4,
  3436. #endif
  3437. &rewriter](OperatorNodeBase* opr) {
  3438. if (!try_conv_dimshuffle_reshape_typecvt(opr) &&
  3439. !try_conv_reformat_nchw42nchw32(opr)
  3440. #if CUDA_VERSION >= 10020
  3441. && !try_conv_reformat_nchw322nchw4(opr)
  3442. #endif
  3443. ) {
  3444. rewriter.auto_replace_outputs(opr);
  3445. }
  3446. };
  3447. opt.graph().iter(on_opr);
  3448. rewriter.apply_inplace();
  3449. MIDOUT_E
  3450. }
  3451. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台