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

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

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