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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982
  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-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or
  10. * implied.
  11. */
  12. #include "megbrain/gopt/basic_arith.h"
  13. #include "megbrain/gopt/gtrans.h"
  14. #include "megbrain/gopt/inference.h"
  15. #include "megbrain/graph/event.h"
  16. #include "megbrain/opr/basic_arith.h"
  17. #include "megbrain/opr/blas.h"
  18. #include "megbrain/opr/dnn/batch_norm.h"
  19. #include "megbrain/opr/dnn/convolution.h"
  20. #include "megbrain/opr/dnn/local.h"
  21. #include "megbrain/opr/dnn/pooling.h"
  22. #include "megbrain/opr/imgproc.h"
  23. #include "megbrain/opr/misc.h"
  24. #include "megbrain/opr/nn_int.h"
  25. #include "megbrain/opr/tensor_manip.h"
  26. #include "megbrain/opr/utility.h"
  27. #include "megbrain/serialization/opr_shallow_copy.h"
  28. #include "megbrain/utils/shared_set.h"
  29. #include "megdnn/opr_param_defs.h"
  30. #include "megdnn/tensor_format.h"
  31. #include "megbrain/opr/internal/megdnn_opr_wrapper.h"
  32. #if MGB_ENABLE_TENSOR_RT
  33. #include "megbrain/tensorrt/tensorrt_opr.h"
  34. #endif
  35. #include "megbrain/gopt/misc.h"
  36. #include "megbrain/utils/hash_ct.h"
  37. #include "midout.h"
  38. MIDOUT_DECL(megbrain_tensor_reformat)
  39. #define MIDOUT_B(tag) \
  40. MIDOUT_BEGIN(megbrain_tensor_reformat, midout_iv(MGB_HASH_STR(tag))) {
  41. #define MIDOUT_E \
  42. } \
  43. MIDOUT_END();
  44. using namespace mgb;
  45. using namespace gopt;
  46. /* ================ TensorReformatPass =============== */
  47. /*!
  48. * \brief relayout placeholder opr
  49. *
  50. * RelayoutPlaceholder oprs act as the placeholders of the ComputingGraph
  51. * during graph opt pass `TensorReformatPass`. These oprs are introduced
  52. * into a ComputingGraph for conveniently discovering further optimize
  53. * opportunities (such as fuse consecutive relayouts, translate into
  54. * optimized implementations). They are canonized to have a shape infer, so
  55. * the ouput's shape can be correctly deduced during the opt pass.
  56. *
  57. * Note that the oprs in the ComputingGraph are only used as intermediate
  58. * representations before being translated to MegBrain oprs, so the
  59. * oprs should not get involved in any actual computing.
  60. */
  61. MGB_DEFINE_OPR_CLASS(TensorReformatPass::RelayoutPlaceholder,
  62. cg::SingleCNOperatorNodeBase) // {
  63. public:
  64. //! relayout type of this opr
  65. enum class LayoutType {
  66. NCHW4_TO_NCHW32, //!< from nchw4 layout to nchw32 layout
  67. NCHW32_TO_NCHW4, //!< from nchw32 layout to nchw4 layout
  68. NCHW4_TO_CHWN4, //!< from nchw4 layout to chwn4 layout
  69. CHWN4_TO_NCHW4, //!< from chwn4 layout to nchw4 layout
  70. NCHW_TO_NCHW4, //!< from nchw layout to nchw4 layout
  71. NCHW_TO_NCHW4_IC_SMALL_CONV, ///< from nchw layout to nchw4 whose
  72. ///< channel size less than 4
  73. NCHW4_TO_NCHW, //!< from nchw4 layout to nchw layout
  74. NCHW_TO_NCHW88, //!< from nchw layout to nchw88 layout
  75. NCHW88_TO_NCHW, //!< from nchw88 layout to nchw layout
  76. WEIGHT_NCHW_TO_NCHW4_DENSE, //!< weight from nchw layout to nchw4
  77. //!< layout
  78. WEIGHT_NCHW_TO_NCHW4_GROUP, //!< group weight from nchw layout to
  79. //!< nchw4 layout
  80. WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV, //!< weight from nchw layout
  81. //!< to nchw4 layout whose
  82. //! channel size less than 4
  83. WEIGHT_NCHW_TO_NCHW88_DENSE, //!< weight from nchw layout to nchw88
  84. //!< layout
  85. WEIGHT_NCHW_TO_NCHW88_GROUP, //!< group weight from nchw layout to
  86. //!< nchw88 layout
  87. WEIGHT_NCHW_TO_NCHW88_CHAN, //!< channel wise weight from nchw layout
  88. //!< to nchw88 layout
  89. //!< the weight layout of input is nchw output is nchw88, special for
  90. //!< shape weight in nchw like {64, 2, 3, 3} to {8, 3, 3, 2, 8}
  91. WEIGHT_HYBIRD_NCHW_NCHW88,
  92. WEIGHT_NCHW_TO_NCHW44_DENSE, //!< weight from nchw layout to nchw44
  93. //!< layout
  94. WEIGHT_NCHW_TO_NCHW44_GROUP, //!< group weight from nchw layout to
  95. //!< nchw44 layout
  96. WEIGHT_NCHW_TO_NCHW44_CHAN, //!< channel wise weight from nchw layout
  97. //!< to nchw44 layout
  98. //!< the weight layout of input is nchw output is nchw44, special for
  99. //!< shape weight in nchw like {64, 2, 3, 3} to {16, 3, 3, 2, 4}
  100. WEIGHT_HYBIRD_NCHW_NCHW44,
  101. WEIGHT_NCHW_TO_NCHW44_DOT_DENSE, //!< weight from NCHW44 layout to
  102. //!< NCHW44_DOT layout dense
  103. WEIGHT_NCHW_TO_NCHW44_DOT_GROUP, //!< weight from NCHW44 layout to
  104. //!< NCHW44_DOT layout group
  105. NCHW32_TO_NCHW, //! <from nchw32 layout to nchw layout
  106. NCHW32_TO_NCHW64, //! <from nchw32 layout to nchw64 layout
  107. NCHW64_TO_NCHW, //! <from nchw64 layout to nchw layout
  108. NCHW64_TO_NCHW4, //! <from nchw64 layout to nchw4 layout
  109. NCHW64_TO_NCHW32, //! <from nchw64 layout to nchw32 layout
  110. NCHW_TO_NCHW64, //! <from nchw layout to nchw64 layout
  111. NCHW_TO_NCHW32, //! <from nchw layout to nchw64 layout
  112. NCHW4_TO_NCHW64, //! <from nchw4 layout to nchw64 layout
  113. };
  114. RelayoutPlaceholder(VarNode* src_var, LayoutType layout_type);
  115. /*!
  116. * \param src_var the input var
  117. * \param layout_type tensor layout transform type of this relayout
  118. * placeholder as described in LayoutType
  119. */
  120. static SymbolVar make(VarNode* src_var, LayoutType layout_type);
  121. LayoutType layout_type() const { return m_layout_type; }
  122. private:
  123. void init_output_static_infer_desc() override;
  124. void scn_do_execute() override;
  125. void init_output_comp_node() override;
  126. const LayoutType m_layout_type;
  127. };
  128. MGB_DYN_TYPE_OBJ_FINAL_IMPL(TensorReformatPass::RelayoutPlaceholder);
  129. TensorReformatPass::RelayoutPlaceholder::RelayoutPlaceholder(
  130. VarNode* src_var, LayoutType layout_type)
  131. : Super(src_var->owner_graph(), {}, "RelayoutPlaceholder", {src_var}),
  132. m_layout_type{layout_type} {
  133. add_input({src_var});
  134. add_equivalence_component<ScalarHash<LayoutType>>(m_layout_type);
  135. add_output(None)->dtype(src_var->dtype());
  136. }
  137. void TensorReformatPass::RelayoutPlaceholder::scn_do_execute() {
  138. mgb_throw(InternalError, "RelayoutPlaceholder opr can not be executed");
  139. }
  140. void TensorReformatPass::RelayoutPlaceholder::init_output_comp_node() {
  141. output(0)->comp_node(input(0)->comp_node());
  142. }
  143. void TensorReformatPass::RelayoutPlaceholder::init_output_static_infer_desc() {
  144. using namespace cg::static_infer;
  145. auto&& mgr = owner_graph()->static_infer_manager();
  146. DepVal deps;
  147. for (auto i : input())
  148. deps.push_back({i, DepType::SHAPE});
  149. auto infer_shape = [this](TensorShape& dst, const InpVal& inp) {
  150. TensorShape inp_shape = inp.val[0].shape();
  151. dst = inp_shape;
  152. if (layout_type() == RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32) {
  153. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  154. dst[0] = inp_shape[0];
  155. dst[1] = inp_shape[1] / 8;
  156. dst[2] = inp_shape[2];
  157. dst[3] = inp_shape[3];
  158. dst[4] = inp_shape[4] * 8;
  159. } else if (layout_type() ==
  160. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4) {
  161. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
  162. dst[0] = inp_shape[0];
  163. dst[1] = inp_shape[1] * 8;
  164. dst[2] = inp_shape[2];
  165. dst[3] = inp_shape[3];
  166. dst[4] = inp_shape[4] / 8;
  167. } else if (layout_type() ==
  168. RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4) {
  169. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  170. dst[0] = inp_shape[1];
  171. dst[1] = inp_shape[2];
  172. dst[2] = inp_shape[3];
  173. dst[3] = inp_shape[0];
  174. dst[4] = inp_shape[4];
  175. } else if (layout_type() ==
  176. RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4) {
  177. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  178. dst[0] = inp_shape[3];
  179. dst[1] = inp_shape[0];
  180. dst[2] = inp_shape[1];
  181. dst[3] = inp_shape[2];
  182. dst[4] = inp_shape[4];
  183. } else if (layout_type() ==
  184. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4 ||
  185. layout_type() == RelayoutPlaceholder::LayoutType::
  186. NCHW_TO_NCHW4_IC_SMALL_CONV) {
  187. if (layout_type() ==
  188. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4) {
  189. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 4 == 0,
  190. "src shape %s", inp_shape.to_string().c_str());
  191. } else {
  192. mgb_assert(layout_type() ==
  193. RelayoutPlaceholder::LayoutType::
  194. NCHW_TO_NCHW4_IC_SMALL_CONV);
  195. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] < 4);
  196. }
  197. dst.ndim = 5;
  198. dst[0] = inp_shape[0];
  199. dst[1] = (inp_shape[1] + 4 - 1) / 4;
  200. dst[2] = inp_shape[2];
  201. dst[3] = inp_shape[3];
  202. dst[4] = 4;
  203. } else if (layout_type() ==
  204. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW) {
  205. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  206. dst.ndim = 4;
  207. dst[0] = inp_shape[0];
  208. dst[1] = inp_shape[1] * 4;
  209. dst[2] = inp_shape[2];
  210. dst[3] = inp_shape[3];
  211. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  212. WEIGHT_NCHW_TO_NCHW4_DENSE ||
  213. layout_type() ==
  214. RelayoutPlaceholder::LayoutType::
  215. WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV) {
  216. if (layout_type() ==
  217. RelayoutPlaceholder::LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE) {
  218. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 4 == 0);
  219. } else {
  220. mgb_assert(layout_type() ==
  221. RelayoutPlaceholder::LayoutType::
  222. WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV);
  223. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] < 4);
  224. }
  225. dst.ndim = 5;
  226. dst[0] = inp_shape[0];
  227. dst[1] = (inp_shape[1] + 4 - 1) / 4;
  228. dst[2] = inp_shape[2];
  229. dst[3] = inp_shape[3];
  230. dst[4] = 4;
  231. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  232. WEIGHT_NCHW_TO_NCHW4_GROUP) {
  233. mgb_assert(inp_shape.ndim == 5 && inp_shape[2] % 4 == 0);
  234. dst.ndim = 6;
  235. dst[0] = inp_shape[0];
  236. dst[1] = inp_shape[1];
  237. dst[2] = inp_shape[2] / 4;
  238. dst[3] = inp_shape[3];
  239. dst[4] = inp_shape[4];
  240. dst[5] = 4;
  241. } else if (layout_type() ==
  242. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW88) {
  243. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 8 == 0);
  244. dst.ndim = 5;
  245. dst[0] = inp_shape[0];
  246. dst[1] = inp_shape[1] / 8;
  247. dst[2] = inp_shape[2];
  248. dst[3] = inp_shape[3];
  249. dst[4] = 8;
  250. } else if (layout_type() ==
  251. RelayoutPlaceholder::LayoutType::NCHW88_TO_NCHW) {
  252. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 8);
  253. dst.ndim = 4;
  254. dst[0] = inp_shape[0];
  255. dst[1] = inp_shape[1] * 8;
  256. dst[2] = inp_shape[2];
  257. dst[3] = inp_shape[3];
  258. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  259. WEIGHT_NCHW_TO_NCHW88_DENSE) {
  260. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 8 == 0 &&
  261. inp_shape[1] % 8 == 0);
  262. dst.ndim = 6;
  263. dst[0] = inp_shape[0] / 8;
  264. dst[1] = inp_shape[1] / 8;
  265. dst[2] = inp_shape[2];
  266. dst[3] = inp_shape[3];
  267. dst[4] = 8;
  268. dst[5] = 8;
  269. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  270. WEIGHT_NCHW_TO_NCHW88_GROUP) {
  271. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 8 == 0 &&
  272. inp_shape[2] % 8 == 0);
  273. dst.ndim = 7;
  274. dst[0] = inp_shape[0];
  275. dst[1] = inp_shape[1] / 8;
  276. dst[2] = inp_shape[2] / 8;
  277. dst[3] = inp_shape[3];
  278. dst[4] = inp_shape[4];
  279. dst[5] = 8;
  280. dst[6] = 8;
  281. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  282. WEIGHT_NCHW_TO_NCHW88_CHAN) {
  283. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] == 1 &&
  284. inp_shape[2] == 1 && inp_shape[0] % 8 == 0);
  285. dst.ndim = 6;
  286. dst[0] = inp_shape[0] / 8;
  287. dst[1] = inp_shape[1];
  288. dst[2] = inp_shape[2];
  289. dst[3] = inp_shape[3];
  290. dst[4] = inp_shape[4];
  291. dst[5] = 8;
  292. } else if (layout_type() ==
  293. RelayoutPlaceholder::LayoutType::WEIGHT_HYBIRD_NCHW_NCHW88) {
  294. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 8 == 0);
  295. dst.ndim = 5;
  296. dst[0] = inp_shape[0] / 8;
  297. dst[1] = inp_shape[2];
  298. dst[2] = inp_shape[3];
  299. dst[3] = inp_shape[1];
  300. dst[4] = 8;
  301. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  302. WEIGHT_NCHW_TO_NCHW44_DENSE ||
  303. layout_type() == RelayoutPlaceholder::LayoutType::
  304. WEIGHT_NCHW_TO_NCHW44_DOT_DENSE) {
  305. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 4 == 0 &&
  306. inp_shape[1] % 4 == 0);
  307. dst.ndim = 6;
  308. dst[0] = inp_shape[0] / 4;
  309. dst[1] = inp_shape[1] / 4;
  310. dst[2] = inp_shape[2];
  311. dst[3] = inp_shape[3];
  312. dst[4] = 4;
  313. dst[5] = 4;
  314. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  315. WEIGHT_NCHW_TO_NCHW44_GROUP ||
  316. layout_type() == RelayoutPlaceholder::LayoutType::
  317. WEIGHT_NCHW_TO_NCHW44_DOT_GROUP) {
  318. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 4 == 0 &&
  319. inp_shape[2] % 4 == 0);
  320. dst.ndim = 7;
  321. dst[0] = inp_shape[0];
  322. dst[1] = inp_shape[1] / 4;
  323. dst[2] = inp_shape[2] / 4;
  324. dst[3] = inp_shape[3];
  325. dst[4] = inp_shape[4];
  326. dst[5] = 4;
  327. dst[6] = 4;
  328. } else if (layout_type() == RelayoutPlaceholder::LayoutType::
  329. WEIGHT_NCHW_TO_NCHW44_CHAN) {
  330. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] == 1 &&
  331. inp_shape[2] == 1 && inp_shape[0] % 4 == 0);
  332. dst.ndim = 6;
  333. dst[0] = inp_shape[0] / 4;
  334. dst[1] = inp_shape[1];
  335. dst[2] = inp_shape[2];
  336. dst[3] = inp_shape[3];
  337. dst[4] = inp_shape[4];
  338. dst[5] = 4;
  339. } else if (layout_type() ==
  340. RelayoutPlaceholder::LayoutType::WEIGHT_HYBIRD_NCHW_NCHW44) {
  341. mgb_assert(inp_shape.ndim == 4 && inp_shape[0] % 4 == 0);
  342. dst.ndim = 5;
  343. dst[0] = inp_shape[0] / 4;
  344. dst[1] = inp_shape[2];
  345. dst[2] = inp_shape[3];
  346. dst[3] = inp_shape[1];
  347. dst[4] = 4;
  348. } else if (layout_type() ==
  349. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW) {
  350. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
  351. dst.ndim = 4;
  352. dst[0] = inp_shape[0];
  353. dst[1] = inp_shape[1] * 32;
  354. dst[2] = inp_shape[2];
  355. dst[3] = inp_shape[3];
  356. } else if (layout_type() ==
  357. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW64) {
  358. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 2 == 0 &&
  359. inp_shape[4] == 32);
  360. dst.ndim = 5;
  361. dst[0] = inp_shape[0];
  362. dst[1] = inp_shape[1] / 2;
  363. dst[2] = inp_shape[2];
  364. dst[3] = inp_shape[3];
  365. dst[4] = 64;
  366. } else if (layout_type() ==
  367. RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW) {
  368. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 64);
  369. dst.ndim = 4;
  370. dst[0] = inp_shape[0];
  371. dst[1] = inp_shape[1] * 64;
  372. dst[2] = inp_shape[2];
  373. dst[3] = inp_shape[3];
  374. } else if (layout_type() ==
  375. RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW4) {
  376. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 64);
  377. dst.ndim = 5;
  378. dst[0] = inp_shape[0];
  379. dst[1] = inp_shape[1] * 16;
  380. dst[2] = inp_shape[2];
  381. dst[3] = inp_shape[3];
  382. dst[4] = 4;
  383. } else if (layout_type() ==
  384. RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW32) {
  385. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 64);
  386. dst.ndim = 5;
  387. dst[0] = inp_shape[0];
  388. dst[1] = inp_shape[1] * 2;
  389. dst[2] = inp_shape[2];
  390. dst[3] = inp_shape[3];
  391. dst[4] = 32;
  392. } else if (layout_type() ==
  393. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW64) {
  394. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 64 == 0, "%s", inp_shape.to_string().c_str());
  395. dst.ndim = 5;
  396. dst[0] = inp_shape[0];
  397. dst[1] = inp_shape[1] / 64;
  398. dst[2] = inp_shape[2];
  399. dst[3] = inp_shape[3];
  400. dst[4] = 64;
  401. } else if (layout_type() ==
  402. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW32) {
  403. mgb_assert(inp_shape.ndim == 4 && inp_shape[1] % 32 == 0);
  404. dst.ndim = 5;
  405. dst[0] = inp_shape[0];
  406. dst[1] = inp_shape[1] / 32;
  407. dst[2] = inp_shape[2];
  408. dst[3] = inp_shape[3];
  409. dst[4] = 32;
  410. } else {
  411. mgb_assert(layout_type() ==
  412. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW64);
  413. mgb_assert(inp_shape.ndim == 5 && inp_shape[1] % 16 == 0);
  414. dst.ndim = 5;
  415. dst[0] = inp_shape[0];
  416. dst[1] = inp_shape[1] / 16;
  417. dst[2] = inp_shape[2];
  418. dst[3] = inp_shape[3];
  419. dst[4] = 64;
  420. }
  421. return true;
  422. };
  423. mgr.register_shape_infer(output(0), {SourceType::DEP, deps, infer_shape});
  424. }
  425. SymbolVar TensorReformatPass::RelayoutPlaceholder::make(
  426. VarNode* src_var, LayoutType layout_type) {
  427. return src_var->owner_graph()
  428. ->insert_opr(
  429. std::make_unique<RelayoutPlaceholder>(src_var, layout_type))
  430. ->output(0);
  431. }
  432. void TensorReformatPass::insert_pass(OptState& opt) const {
  433. opt.set_var_replace_check_flag(m_var_replace_check_flag);
  434. auto rewriter = opt.graph().make_rewriter();
  435. VarNodeArray new_inp_cache;
  436. auto on_opr = [this, &opt, &rewriter,
  437. &new_inp_cache](OperatorNodeBase* opr) {
  438. auto it = m_opr_replace_func.find(opr->dyn_typeinfo());
  439. if (it != m_opr_replace_func.end()) {
  440. auto& new_inp = new_inp_cache;
  441. new_inp.clear();
  442. new_inp.reserve(opr->input().size());
  443. for (auto&& inp : opr->input()) {
  444. new_inp.push_back(rewriter.get_var(inp));
  445. }
  446. auto new_opr = (it->second)(opr, new_inp);
  447. auto &&out0 = opr->output(), &&out1 = new_opr->output();
  448. mgb_assert(out0.size() == out1.size(),
  449. "bad opr replace: src=%s{%s} dst=%s{%s}, "
  450. "src.size=%zu "
  451. "dst.size=%zu",
  452. opr->cname(), opr->dyn_typeinfo()->name,
  453. new_opr->cname(), new_opr->dyn_typeinfo()->name,
  454. out0.size(), out1.size());
  455. for (size_t i = 0; i < out0.size(); ++i) {
  456. if (!out0[i]->contain_flag(VarNode::Flag::VOLATILE_CONTENT)) {
  457. mgb_assert(!out1[i]->contain_flag(
  458. VarNode::Flag::VOLATILE_CONTENT));
  459. auto src = out0[i];
  460. auto dst = out1[i];
  461. if (opt.graph().endpoint_contain(src)) {
  462. // additional process on endpoint var node
  463. dst = on_graph_endpoint_var(dst, src);
  464. }
  465. rewriter.replace_var(src, dst, nullptr);
  466. }
  467. }
  468. } else {
  469. rewriter.auto_replace_outputs(opr);
  470. }
  471. };
  472. opt.graph().iter(on_opr);
  473. rewriter.apply_inplace();
  474. }
  475. void TensorReformatPass::translate_pass(OptState& opt) const {
  476. ThinHashMap<RelayoutPlaceholder::LayoutType,
  477. thin_function<VarNode*(VarNode*)>>
  478. reformat;
  479. using LayoutType = RelayoutPlaceholder::LayoutType;
  480. reformat[LayoutType::NCHW4_TO_CHWN4] = [](VarNode* inp) -> VarNode* {
  481. megdnn::param::RelayoutFormat param;
  482. param.mode = megdnn::param::RelayoutFormat::Mode::NCHW4_CHWN4;
  483. auto reformat = opr::RelayoutFormat::make(inp, param);
  484. return reformat.node();
  485. };
  486. reformat[LayoutType::CHWN4_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
  487. megdnn::param::RelayoutFormat param;
  488. param.mode = megdnn::param::RelayoutFormat::Mode::CHWN4_NCHW4;
  489. auto reformat = opr::RelayoutFormat::make(inp, param);
  490. return reformat.node();
  491. };
  492. reformat[LayoutType::NCHW4_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
  493. auto x = SymbolVar(inp);
  494. auto xshp = opr::GetVarShape::make(x);
  495. auto cv = [&x](int v) { return x.make_scalar(v); };
  496. auto sub = [&xshp, &cv](int idx) {
  497. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  498. };
  499. auto tshp0 = opr::Concat::make(
  500. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)}, 0),
  501. tshp1 = opr::Concat::make(
  502. {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
  503. auto y0 = opr::Reshape::make(x, tshp0);
  504. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  505. auto y2 = opr::Reshape::make(y1, tshp1);
  506. return y2.node();
  507. };
  508. reformat[LayoutType::NCHW32_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
  509. auto x = SymbolVar(inp);
  510. auto xshp = opr::GetVarShape::make(x);
  511. auto cv = [&x](int v) { return x.make_scalar(v); };
  512. auto sub = [&xshp, &cv](int idx) {
  513. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  514. };
  515. auto tshp0 = opr::Concat::make(
  516. {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8}, 0),
  517. tshp1 = opr::Concat::make(
  518. {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
  519. auto y0 = opr::Reshape::make(x, tshp0);
  520. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  521. auto y2 = opr::Reshape::make(y1, tshp1);
  522. return y2.node();
  523. };
  524. reformat[LayoutType::NCHW_TO_NCHW4_IC_SMALL_CONV] =
  525. [](VarNode* inp) -> VarNode* {
  526. auto x = SymbolVar(inp);
  527. auto y = opr::RelayoutFormat::make(
  528. x, megdnn::param::RelayoutFormat::Mode::NCHW_NCHW4_IC_SMALL);
  529. return y.node();
  530. };
  531. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV] =
  532. [](VarNode* inp) -> VarNode* {
  533. auto x = SymbolVar(inp);
  534. auto y = opr::RelayoutFormat::make(
  535. x, megdnn::param::RelayoutFormat::Mode::
  536. NCHW_NCHW4_IC_SMALL_CONV_DENSE_WEIGHT);
  537. return y.node();
  538. };
  539. reformat[LayoutType::NCHW_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
  540. auto x = SymbolVar(inp);
  541. auto xshp = opr::GetVarShape::make(x);
  542. auto cv = [&x](int v) { return x.make_scalar(v); };
  543. auto sub = [&xshp, &cv](int idx) {
  544. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  545. };
  546. auto tshp0 = opr::Concat::make(
  547. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
  548. auto y0 = opr::Reshape::make(x, tshp0);
  549. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  550. return y1.node();
  551. };
  552. reformat[LayoutType::NCHW4_TO_NCHW] = [](VarNode* inp) -> VarNode* {
  553. auto x = SymbolVar(inp);
  554. auto xshp = opr::GetVarShape::make(x);
  555. auto cv = [&x](int v) { return x.make_scalar(v); };
  556. auto sub = [&xshp, &cv](int idx) {
  557. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  558. };
  559. auto tshp0 = opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
  560. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  561. auto y1 = opr::Reshape::make(y0, tshp0);
  562. return y1.node();
  563. };
  564. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_DENSE] =
  565. [](VarNode* inp) -> VarNode* {
  566. auto x = SymbolVar(inp);
  567. auto xshp = opr::GetVarShape::make(x);
  568. auto cv = [&x](int v) { return x.make_scalar(v); };
  569. auto sub = [&xshp, &cv](int idx) {
  570. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  571. };
  572. auto tshp0 = opr::Concat::make(
  573. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
  574. tshp1 = opr::Concat::make(
  575. {sub(0), sub(1) / 4, sub(2), sub(3), cv(4)}, 0);
  576. auto y0 = opr::Reshape::make(x, tshp0);
  577. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  578. auto y2 = opr::Reshape::make(y1, tshp1);
  579. return y2.node();
  580. };
  581. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW4_GROUP] =
  582. [](VarNode* inp) -> VarNode* {
  583. auto x = SymbolVar(inp);
  584. auto xshp = opr::GetVarShape::make(x);
  585. auto cv = [&x](int v) { return x.make_scalar(v); };
  586. auto sub = [&xshp, &cv](int idx) {
  587. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  588. };
  589. auto tshp0 = opr::Concat::make(
  590. {sub(0), sub(1), sub(2) / 4, cv(4), sub(3), sub(4)}, 0),
  591. tshp1 = opr::Concat::make(
  592. {sub(0), sub(1), sub(2) / 4, sub(3), sub(4), cv(4)}, 0);
  593. auto y0 = opr::Reshape::make(x, tshp0);
  594. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 2, 4, 5, 3});
  595. auto y2 = opr::Reshape::make(y1, tshp1);
  596. return y2.node();
  597. };
  598. reformat[LayoutType::NCHW_TO_NCHW88] = [](VarNode* inp) -> VarNode* {
  599. auto x = SymbolVar(inp);
  600. auto xshp = opr::GetVarShape::make(x);
  601. auto cv = [&x](int v) { return x.make_scalar(v); };
  602. auto sub = [&xshp, &cv](int idx) {
  603. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  604. };
  605. auto tshp0 = opr::Concat::make(
  606. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3)}, 0),
  607. tshp1 = opr::Concat::make(
  608. {sub(0), sub(1) / 8, sub(2), sub(3), cv(8)}, 0);
  609. auto y0 = opr::Reshape::make(x, tshp0);
  610. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  611. auto y2 = opr::Reshape::make(y1, tshp1);
  612. return y2.node();
  613. };
  614. reformat[LayoutType::NCHW88_TO_NCHW] = [](VarNode* inp) -> VarNode* {
  615. auto x = SymbolVar(inp);
  616. auto xshp = opr::GetVarShape::make(x);
  617. auto cv = [&x](int v) { return x.make_scalar(v); };
  618. auto sub = [&xshp, &cv](int idx) {
  619. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  620. };
  621. auto tshp0 = opr::Concat::make({sub(0), sub(1) * 8, sub(2), sub(3)}, 0);
  622. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  623. auto y1 = opr::Reshape::make(y0, tshp0);
  624. return y1.node();
  625. };
  626. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_DENSE] =
  627. [](VarNode* inp) -> VarNode* {
  628. auto x = SymbolVar(inp);
  629. auto xshp = opr::GetVarShape::make(x);
  630. auto cv = [&x](int v) { return x.make_scalar(v); };
  631. auto sub = [&xshp, &cv](int idx) {
  632. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  633. };
  634. auto tshp0 = opr::Concat::make(
  635. {sub(0) / 8, cv(8), sub(1) / 8, cv(8), sub(2), sub(3)}, 0),
  636. tshp1 = opr::Concat::make(
  637. {sub(0) / 8, sub(1) / 8, sub(2), sub(3), cv(8), cv(8)}, 0);
  638. auto y0 = opr::Reshape::make(x, tshp0);
  639. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 3, 1});
  640. auto y2 = opr::Reshape::make(y1, tshp1);
  641. return y2.node();
  642. };
  643. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_GROUP] =
  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({sub(0), sub(1) / 8, cv(8), sub(2) / 8,
  652. cv(8), sub(3), sub(4)},
  653. 0),
  654. tshp1 = opr::Concat::make({sub(0), sub(1) / 8, sub(2) / 8, sub(3),
  655. sub(4), cv(8), cv(8)},
  656. 0);
  657. auto y0 = opr::Reshape::make(x, tshp0);
  658. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 4, 2});
  659. auto y2 = opr::Reshape::make(y1, tshp1);
  660. return y2.node();
  661. };
  662. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW88_CHAN] =
  663. [](VarNode* inp) -> VarNode* {
  664. auto x = SymbolVar(inp);
  665. auto xshp = opr::GetVarShape::make(x);
  666. auto cv = [&x](int v) { return x.make_scalar(v); };
  667. auto sub = [&xshp, &cv](int idx) {
  668. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  669. };
  670. auto tshp0 = opr::Concat::make(
  671. {sub(0) / 8, cv(8), sub(1), sub(2), sub(3), sub(4)}, 0),
  672. tshp1 = opr::Concat::make(
  673. {sub(0) / 8, sub(1), sub(2), sub(3), sub(4), cv(8)}, 0);
  674. auto y0 = opr::Reshape::make(x, tshp0);
  675. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 3, 4, 5, 1});
  676. auto y2 = opr::Reshape::make(y1, tshp1);
  677. return y2.node();
  678. };
  679. reformat[LayoutType::WEIGHT_HYBIRD_NCHW_NCHW88] =
  680. [](VarNode* inp) -> VarNode* {
  681. auto x = SymbolVar(inp);
  682. auto xshp = opr::GetVarShape::make(x);
  683. auto cv = [&x](int v) { return x.make_scalar(v); };
  684. auto sub = [&xshp, &cv](int idx) {
  685. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  686. };
  687. auto tshp0 = opr::Concat::make(
  688. {sub(0) / 8, cv(8), sub(1), sub(2), sub(3)}, 0),
  689. tshp1 = opr::Concat::make(
  690. {sub(0) / 8, sub(2), sub(3), sub(1), cv(8)}, 0);
  691. auto y0 = opr::Reshape::make(x, tshp0);
  692. auto y1 = opr::Dimshuffle::make(y0, {0, 3, 4, 2, 1});
  693. auto y2 = opr::Reshape::make(y1, tshp1);
  694. return y2.node();
  695. };
  696. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DENSE] =
  697. [](VarNode* inp) -> VarNode* {
  698. auto x = SymbolVar(inp);
  699. auto xshp = opr::GetVarShape::make(x);
  700. auto cv = [&x](int v) { return x.make_scalar(v); };
  701. auto sub = [&xshp, &cv](int idx) {
  702. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  703. };
  704. auto tshp0 = opr::Concat::make(
  705. {sub(0) / 4, cv(4), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
  706. tshp1 = opr::Concat::make(
  707. {sub(0) / 4, sub(1) / 4, sub(2), sub(3), cv(4), cv(4)}, 0);
  708. auto y0 = opr::Reshape::make(x, tshp0);
  709. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 3, 1});
  710. auto y2 = opr::Reshape::make(y1, tshp1);
  711. return y2.node();
  712. };
  713. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_GROUP] =
  714. [](VarNode* inp) -> VarNode* {
  715. auto x = SymbolVar(inp);
  716. auto xshp = opr::GetVarShape::make(x);
  717. auto cv = [&x](int v) { return x.make_scalar(v); };
  718. auto sub = [&xshp, &cv](int idx) {
  719. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  720. };
  721. auto tshp0 = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2) / 4,
  722. cv(4), sub(3), sub(4)},
  723. 0),
  724. tshp1 = opr::Concat::make({sub(0), sub(1) / 4, sub(2) / 4, sub(3),
  725. sub(4), cv(4), cv(4)},
  726. 0);
  727. auto y0 = opr::Reshape::make(x, tshp0);
  728. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 4, 2});
  729. auto y2 = opr::Reshape::make(y1, tshp1);
  730. return y2.node();
  731. };
  732. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_CHAN] =
  733. [](VarNode* inp) -> VarNode* {
  734. auto x = SymbolVar(inp);
  735. auto xshp = opr::GetVarShape::make(x);
  736. auto cv = [&x](int v) { return x.make_scalar(v); };
  737. auto sub = [&xshp, &cv](int idx) {
  738. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  739. };
  740. auto tshp0 = opr::Concat::make(
  741. {sub(0) / 4, cv(4), sub(1), sub(2), sub(3), sub(4)}, 0),
  742. tshp1 = opr::Concat::make(
  743. {sub(0) / 4, sub(1), sub(2), sub(3), sub(4), cv(4)}, 0);
  744. auto y0 = opr::Reshape::make(x, tshp0);
  745. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 3, 4, 5, 1});
  746. auto y2 = opr::Reshape::make(y1, tshp1);
  747. return y2.node();
  748. };
  749. reformat[LayoutType::WEIGHT_HYBIRD_NCHW_NCHW44] =
  750. [](VarNode* inp) -> VarNode* {
  751. auto x = SymbolVar(inp);
  752. auto xshp = opr::GetVarShape::make(x);
  753. auto cv = [&x](int v) { return x.make_scalar(v); };
  754. auto sub = [&xshp, &cv](int idx) {
  755. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  756. };
  757. auto tshp0 = opr::Concat::make(
  758. {sub(0) / 4, cv(4), sub(1), sub(2), sub(3)}, 0),
  759. tshp1 = opr::Concat::make(
  760. {sub(0) / 4, sub(2), sub(3), sub(1), cv(4)}, 0);
  761. auto y0 = opr::Reshape::make(x, tshp0);
  762. auto y1 = opr::Dimshuffle::make(y0, {0, 3, 4, 2, 1});
  763. auto y2 = opr::Reshape::make(y1, tshp1);
  764. return y2.node();
  765. };
  766. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DOT_DENSE] =
  767. [](VarNode* inp) -> VarNode* {
  768. auto x = SymbolVar(inp);
  769. auto xshp = opr::GetVarShape::make(x);
  770. auto cv = [&x](int v) { return x.make_scalar(v); };
  771. auto sub = [&xshp, &cv](int idx) {
  772. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  773. };
  774. auto tshp0 = opr::Concat::make(
  775. {sub(0) / 4, cv(4), sub(1) / 4, cv(4), sub(2), sub(3)}, 0),
  776. tshp1 = opr::Concat::make(
  777. {sub(0) / 4, sub(1) / 4, sub(2), sub(3), cv(4), cv(4)}, 0);
  778. auto y0 = opr::Reshape::make(x, tshp0);
  779. auto y1 = opr::Dimshuffle::make(y0, {0, 2, 4, 5, 1, 3});
  780. auto y2 = opr::Reshape::make(y1, tshp1);
  781. return y2.node();
  782. };
  783. reformat[LayoutType::WEIGHT_NCHW_TO_NCHW44_DOT_GROUP] =
  784. [](VarNode* inp) -> VarNode* {
  785. auto x = SymbolVar(inp);
  786. auto xshp = opr::GetVarShape::make(x);
  787. auto cv = [&x](int v) { return x.make_scalar(v); };
  788. auto sub = [&xshp, &cv](int idx) {
  789. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  790. };
  791. auto tshp0 = opr::Concat::make({sub(0), sub(1) / 4, cv(4), sub(2) / 4,
  792. cv(4), sub(3), sub(4)},
  793. 0),
  794. tshp1 = opr::Concat::make({sub(0), sub(1) / 4, sub(2) / 4, sub(3),
  795. sub(4), cv(4), cv(4)},
  796. 0);
  797. auto y0 = opr::Reshape::make(x, tshp0);
  798. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 5, 6, 2, 4});
  799. auto y2 = opr::Reshape::make(y1, tshp1);
  800. return y2.node();
  801. };
  802. reformat[LayoutType::NCHW32_TO_NCHW] = [](VarNode* inp) -> VarNode* {
  803. auto x = SymbolVar(inp);
  804. auto xshp = opr::GetVarShape::make(x);
  805. auto cv = [&x](int v) { return x.make_scalar(v); };
  806. auto sub = [&xshp, &cv](int idx) {
  807. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  808. };
  809. auto tshp0 =
  810. opr::Concat::make({sub(0), sub(1) * 32, sub(2), sub(3)}, 0);
  811. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  812. auto y1 = opr::Reshape::make(y0, tshp0);
  813. return y1.node();
  814. };
  815. reformat[LayoutType::NCHW32_TO_NCHW64] = [](VarNode* inp) -> VarNode* {
  816. auto x = SymbolVar(inp);
  817. auto xshp = opr::GetVarShape::make(x);
  818. auto cv = [&x](int v) { return x.make_scalar(v); };
  819. auto sub = [&xshp, &cv](int idx) {
  820. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  821. };
  822. auto tshp0 = opr::Concat::make(
  823. {sub(0), sub(1) / 2, cv(2), sub(2), sub(3), sub(4)}, 0),
  824. tshp1 = opr::Concat::make(
  825. {sub(0), sub(1) / 2, sub(2), sub(3), sub(4) * 2}, 0);
  826. auto y0 = opr::Reshape::make(x, tshp0);
  827. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  828. auto y2 = opr::Reshape::make(y1, tshp1);
  829. return y2.node();
  830. };
  831. reformat[LayoutType::NCHW64_TO_NCHW] = [](VarNode* inp) -> VarNode* {
  832. auto x = SymbolVar(inp);
  833. auto xshp = opr::GetVarShape::make(x);
  834. auto cv = [&x](int v) { return x.make_scalar(v); };
  835. auto sub = [&xshp, &cv](int idx) {
  836. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  837. };
  838. auto tshp0 =
  839. opr::Concat::make({sub(0), sub(1) * 64, sub(2), sub(3)}, 0);
  840. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  841. auto y1 = opr::Reshape::make(y0, tshp0);
  842. return y1.node();
  843. };
  844. reformat[LayoutType::NCHW64_TO_NCHW4] = [](VarNode* inp) -> VarNode* {
  845. auto x = SymbolVar(inp);
  846. auto xshp = opr::GetVarShape::make(x);
  847. auto cv = [&x](int v) { return x.make_scalar(v); };
  848. auto sub = [&xshp, &cv](int idx) {
  849. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  850. };
  851. auto tshp0 = opr::Concat::make(
  852. {sub(0), sub(1), sub(2), sub(3), sub(4) / 4, cv(4)}, 0),
  853. tshp1 = opr::Concat::make(
  854. {sub(0), sub(1) * 16, sub(2), sub(3), cv(4)}, 0);
  855. auto y0 = opr::Reshape::make(x, tshp0);
  856. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  857. auto y2 = opr::Reshape::make(y1, tshp1);
  858. return y2.node();
  859. };
  860. reformat[LayoutType::NCHW64_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
  861. auto x = SymbolVar(inp);
  862. auto xshp = opr::GetVarShape::make(x);
  863. auto cv = [&x](int v) { return x.make_scalar(v); };
  864. auto sub = [&xshp, &cv](int idx) {
  865. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  866. };
  867. auto tshp0 = opr::Concat::make(
  868. {sub(0), sub(1), sub(2), sub(3), sub(4) / 32, cv(32)}, 0),
  869. tshp1 = opr::Concat::make(
  870. {sub(0), sub(1) * 2, sub(2), sub(3), cv(32)}, 0);
  871. auto y0 = opr::Reshape::make(x, tshp0);
  872. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  873. auto y2 = opr::Reshape::make(y1, tshp1);
  874. return y2.node();
  875. };
  876. reformat[LayoutType::NCHW_TO_NCHW64] = [](VarNode* inp) -> VarNode* {
  877. megdnn::param::RelayoutFormat param;
  878. param.mode = megdnn::param::RelayoutFormat::Mode::NCHW_NCHW64;
  879. auto reformat = opr::RelayoutFormat::make(inp, param);
  880. return reformat.node();
  881. };
  882. reformat[LayoutType::NCHW_TO_NCHW32] = [](VarNode* inp) -> VarNode* {
  883. auto x = SymbolVar(inp);
  884. auto xshp = opr::GetVarShape::make(x);
  885. auto cv = [&x](int v) { return x.make_scalar(v); };
  886. auto sub = [&xshp, &cv](int idx) {
  887. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  888. };
  889. auto tshp0 = opr::Concat::make(
  890. {sub(0), sub(1) / 32, cv(32), sub(2), sub(3)}, 0);
  891. auto y0 = opr::Reshape::make(x, tshp0);
  892. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  893. return y1.node();
  894. };
  895. reformat[LayoutType::NCHW4_TO_NCHW64] = [](VarNode* inp) -> VarNode* {
  896. auto x = SymbolVar(inp);
  897. auto xshp = opr::GetVarShape::make(x);
  898. auto cv = [&x](int v) { return x.make_scalar(v); };
  899. auto sub = [&xshp, &cv](int idx) {
  900. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  901. };
  902. auto tshp0 = opr::Concat::make(
  903. {sub(0), sub(1) / 16, cv(16), sub(2), sub(3), sub(4)}, 0),
  904. tshp1 = opr::Concat::make(
  905. {sub(0), sub(1) / 16, sub(2), sub(3), sub(4) * 16}, 0);
  906. auto y0 = opr::Reshape::make(x, tshp0);
  907. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  908. auto y2 = opr::Reshape::make(y1, tshp1);
  909. return y2.node();
  910. };
  911. auto rewriter = opt.graph().make_rewriter();
  912. auto on_opr = [&reformat, &rewriter](OperatorNodeBase* opr) {
  913. if (opr->same_type<RelayoutPlaceholder>()) {
  914. auto ph = try_cast_as_op<RelayoutPlaceholder>(opr);
  915. auto new_inp = rewriter.get_var(opr->input(0));
  916. mgb_assert(reformat.count(ph->layout_type()),
  917. "no replace rule can be found for layout_type(%u)",
  918. static_cast<uint32_t>(ph->layout_type()));
  919. auto new_var = reformat[ph->layout_type()](new_inp);
  920. rewriter.replace_var(opr->output(0), new_var,
  921. mgb_cstr_log("replace relayout placeholder"));
  922. return;
  923. }
  924. rewriter.auto_replace_outputs(opr);
  925. };
  926. opt.graph().iter(on_opr);
  927. rewriter.apply_inplace();
  928. }
  929. void TensorReformatPass::apply(OptState& opt) const {
  930. MIDOUT_B("TensorReformatPass::apply")
  931. insert_pass(opt);
  932. translate_pass(opt);
  933. MIDOUT_E
  934. }
  935. /* ================ EnableTensorCorePass =============== */
  936. VarNode* EnableTensorCorePass::on_graph_endpoint_var(VarNode* new_var,
  937. VarNode* orig_var) const {
  938. if (!orig_var->shape().eq_shape(new_var->shape())) {
  939. return RelayoutPlaceholder::make(
  940. new_var,
  941. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4)
  942. .node();
  943. }
  944. return new_var;
  945. }
  946. std::unique_ptr<EnableTensorCorePass>
  947. EnableTensorCorePass::make_tensorcore_converter() {
  948. MIDOUT_B("EnableTensorCorePass::make")
  949. // replace rule for conv bias opr
  950. auto replace_conv_bias_opr = [](OperatorNodeBase* opr,
  951. const VarNodeArray& new_inp) {
  952. using Param = megdnn::param::ConvBias;
  953. using Format = Param::Format;
  954. using Sparse = Param::Sparse;
  955. mgb_assert(opr->input().size() == new_inp.size());
  956. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  957. if (conv_bias.param().format != Format::NCHW4 ||
  958. conv_bias.output(0)->dtype().enumv() != DTypeEnum::QuantizedS8) {
  959. size_t nr_inps = opr->input().size();
  960. bool shape_has_changed = false;
  961. for (size_t i = 0; i < nr_inps; ++i) {
  962. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  963. shape_has_changed = true;
  964. }
  965. }
  966. MGB_MARK_USED_VAR(shape_has_changed);
  967. mgb_assert(
  968. !shape_has_changed,
  969. "EnableTensorCorePass assumes that the shape of inputs of"
  970. "ConvBias operators whose output dtype is not QuantizedS8 "
  971. "can not be changed in this opt pass");
  972. return serialization::copy_opr_shallow(*opr, new_inp,
  973. opr->config());
  974. }
  975. mgb_assert(opr->input(1)->shape().eq_shape(new_inp[1]->shape()),
  976. "EnableTensorCorePass assumes that filter tensor of "
  977. "conv_bias operator can not be changed by other operators");
  978. VarNode* orig_filter = opr->input(1);
  979. auto is_nchw4 = [](TensorShape shape) -> bool {
  980. return shape.ndim == 5 && shape[4] == 4;
  981. };
  982. auto is_nchw32 = [](TensorShape shape) -> bool {
  983. return shape.ndim == 5 && shape[4] == 32;
  984. };
  985. bool can_replace_nchw32 = false;
  986. VarNode *src = nullptr, *weight = nullptr, *bias = nullptr,
  987. *z_inp = nullptr;
  988. // process src tensor
  989. if (is_nchw4(new_inp[0]->shape())) { // new input is NCHW4 layout
  990. size_t group = 1, icpg, ocpg;
  991. if (conv_bias.param().sparse == Sparse::DENSE) {
  992. icpg = orig_filter->shape()[1] * 4;
  993. ocpg = orig_filter->shape()[0];
  994. } else {
  995. mgb_assert(conv_bias.param().sparse == Sparse::GROUP);
  996. group = orig_filter->shape()[0];
  997. icpg = orig_filter->shape()[2];
  998. ocpg = orig_filter->shape()[1];
  999. if (icpg == 1 && ocpg == 1) { // channel wise conv
  1000. group *= 4;
  1001. } else {
  1002. icpg *= 4;
  1003. }
  1004. }
  1005. // nchw32 layout need that input width and height are larger than 3
  1006. size_t ih = new_inp[0]->shape()[2], iw = new_inp[0]->shape()[3];
  1007. if (group == 1 && ocpg % 32 == 0 && icpg % 32 == 0 && ih >= 3 &&
  1008. iw >= 3) {
  1009. auto symvar = RelayoutPlaceholder::make(
  1010. new_inp[0],
  1011. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
  1012. src = symvar.node();
  1013. can_replace_nchw32 = true;
  1014. } else {
  1015. src = new_inp[0];
  1016. }
  1017. } else { // new input is NCHW32 layout
  1018. mgb_assert(is_nchw32(new_inp[0]->shape()));
  1019. size_t group = 1, ocpg;
  1020. if (conv_bias.param().sparse == Sparse::DENSE) {
  1021. ocpg = orig_filter->shape()[0];
  1022. } else {
  1023. mgb_assert(conv_bias.param().sparse == Sparse::GROUP);
  1024. size_t icpg = orig_filter->shape()[2];
  1025. ocpg = orig_filter->shape()[1];
  1026. if (icpg == 1 && ocpg == 1) {
  1027. group *= 4;
  1028. } else {
  1029. icpg *= 4;
  1030. }
  1031. }
  1032. size_t ih = new_inp[0]->shape()[2], iw = new_inp[0]->shape()[3];
  1033. if (group == 1 && ocpg % 32 == 0 && ih >= 3 && iw >= 3) {
  1034. can_replace_nchw32 = true;
  1035. src = new_inp[0];
  1036. } else {
  1037. auto symvar = RelayoutPlaceholder::make(
  1038. new_inp[0],
  1039. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
  1040. src = symvar.node();
  1041. }
  1042. }
  1043. // process filter tensor
  1044. if (can_replace_nchw32) {
  1045. auto symvar = RelayoutPlaceholder::make(
  1046. new_inp[1],
  1047. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
  1048. weight = symvar.node();
  1049. } else {
  1050. weight = new_inp[1];
  1051. }
  1052. if (new_inp.size() == 2) {
  1053. if (can_replace_nchw32) {
  1054. auto param = conv_bias.param();
  1055. param.format = Format::NCHW32;
  1056. auto new_opr = opr::ConvBiasForward::make(
  1057. src, weight, param, conv_bias.execution_policy(),
  1058. conv_bias.config());
  1059. return new_opr.node()->owner_opr();
  1060. } else {
  1061. VarNodeArray inps{src, weight};
  1062. auto new_opr = serialization::copy_opr_shallow(*opr, inps,
  1063. opr->config());
  1064. return new_opr;
  1065. }
  1066. }
  1067. auto process_inp = [&](VarNode* inp) -> VarNode* {
  1068. if (can_replace_nchw32) {
  1069. if (is_nchw4(inp->shape())) {
  1070. auto symvar = RelayoutPlaceholder::make(
  1071. inp,
  1072. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
  1073. return symvar.node();
  1074. } else {
  1075. mgb_assert(is_nchw32(inp->shape()));
  1076. return inp;
  1077. }
  1078. } else {
  1079. if (is_nchw4(inp->shape())) {
  1080. return inp;
  1081. } else {
  1082. mgb_assert(is_nchw32(inp->shape()));
  1083. auto symvar = RelayoutPlaceholder::make(
  1084. inp,
  1085. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
  1086. return symvar.node();
  1087. }
  1088. }
  1089. };
  1090. // process bias tensor
  1091. bias = process_inp(new_inp[2]);
  1092. if (new_inp.size() == 3) {
  1093. if (can_replace_nchw32) {
  1094. auto param = conv_bias.param();
  1095. param.format = Format::NCHW32;
  1096. auto new_opr = opr::ConvBiasForward::make(
  1097. src, weight, bias, param, conv_bias.execution_policy(),
  1098. conv_bias.config());
  1099. return new_opr.node()->owner_opr();
  1100. } else {
  1101. VarNodeArray inps{src, weight, bias};
  1102. auto new_opr = serialization::copy_opr_shallow(*opr, inps,
  1103. opr->config());
  1104. return new_opr;
  1105. }
  1106. }
  1107. // process z_inp tensor
  1108. z_inp = process_inp(new_inp[3]);
  1109. if (can_replace_nchw32) {
  1110. auto param = conv_bias.param();
  1111. param.format = Format::NCHW32;
  1112. auto new_opr = opr::ConvBiasForward::make(
  1113. src, weight, bias, z_inp, param,
  1114. conv_bias.execution_policy(), conv_bias.config());
  1115. return new_opr.node()->owner_opr();
  1116. }
  1117. VarNodeArray inps{src, weight, bias, z_inp};
  1118. auto new_opr =
  1119. serialization::copy_opr_shallow(*opr, inps, opr->config());
  1120. return new_opr;
  1121. };
  1122. // replace rule for elemwise like opr
  1123. // for oprs support NCHW4 and NCHW32 layout
  1124. auto replace_elemwise_like_opr = [](OperatorNodeBase* opr,
  1125. const VarNodeArray new_inp) {
  1126. mgb_assert(opr->input().size() == new_inp.size());
  1127. size_t nr_inps = new_inp.size();
  1128. size_t nr_shape_changed = 0;
  1129. for (size_t i = 0; i < nr_inps; ++i) {
  1130. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1131. nr_shape_changed++;
  1132. }
  1133. }
  1134. if (nr_shape_changed) {
  1135. auto inps = new_inp;
  1136. if (nr_shape_changed >=
  1137. nr_inps / 2) { // NCHW32 > NCHW4 -> use NCHW32
  1138. for (size_t i = 0; i < nr_inps; ++i) {
  1139. if (opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1140. auto symvar = RelayoutPlaceholder::make(
  1141. new_inp[i], RelayoutPlaceholder::LayoutType::
  1142. NCHW4_TO_NCHW32);
  1143. inps[i] = symvar.node();
  1144. }
  1145. }
  1146. } else { // NCHW32 < NCHW4 -> use NCHW4
  1147. for (size_t i = 0; i < nr_inps; ++i) {
  1148. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1149. auto symvar = RelayoutPlaceholder::make(
  1150. new_inp[i], RelayoutPlaceholder::LayoutType::
  1151. NCHW32_TO_NCHW4);
  1152. inps[i] = symvar.node();
  1153. }
  1154. }
  1155. }
  1156. return serialization::copy_opr_shallow(*opr, inps, opr->config());
  1157. }
  1158. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1159. };
  1160. // for oprs only supports NCHW4 layout
  1161. auto replace_inps_to_nchw4 = [](OperatorNodeBase* opr,
  1162. const VarNodeArray new_inp) {
  1163. mgb_assert(opr->input().size() == new_inp.size());
  1164. VarNodeArray inps = new_inp;
  1165. for (size_t i = 0; i < opr->input().size(); ++i) {
  1166. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1167. mgb_assert(opr->input(i)->shape().ndim == 5 &&
  1168. opr->input(i)->shape()[4] == 4);
  1169. mgb_assert(new_inp[i]->shape().ndim == 5 &&
  1170. new_inp[i]->shape()[4] == 32);
  1171. auto symvar = RelayoutPlaceholder::make(
  1172. new_inp[i],
  1173. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
  1174. inps[i] = symvar.node();
  1175. }
  1176. }
  1177. auto new_opr =
  1178. serialization::copy_opr_shallow(*opr, inps, opr->config());
  1179. return new_opr;
  1180. };
  1181. auto replace_non_nchw4_opr = [](OperatorNodeBase* opr,
  1182. const VarNodeArray new_inp) {
  1183. size_t nr_inps = opr->input().size();
  1184. bool shape_has_changed = false;
  1185. for (size_t i = 0; i < nr_inps; ++i) {
  1186. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1187. shape_has_changed = true;
  1188. }
  1189. }
  1190. mgb_assert(!shape_has_changed,
  1191. "EnableTensorCorePass assumes that inputs' shape of "
  1192. "non-nchw4 operators "
  1193. "can not be changed in this opt "
  1194. "pass");
  1195. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1196. };
  1197. auto replace_warp_affine_opr =
  1198. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1199. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1200. using Param = opr::WarpAffineForward::Param;
  1201. using Format = Param::Format;
  1202. mgb_assert(opr->input().size() == new_inp.size());
  1203. auto& warp = opr->cast_final_safe<opr::WarpAffineForward>();
  1204. if (warp.param().format != Format::NCHW4) {
  1205. return replace_non_nchw4_opr(opr, new_inp);
  1206. }
  1207. return replace_inps_to_nchw4(opr, new_inp);
  1208. };
  1209. auto replace_warp_perspective_opr =
  1210. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1211. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1212. using Param = opr::WarpPerspectiveForward::Param;
  1213. using Format = Param::Format;
  1214. mgb_assert(opr->input().size() == new_inp.size());
  1215. auto& warp =
  1216. opr->cast_final_safe<opr::WarpPerspectiveForward>();
  1217. if (warp.param().format != Format::NCHW4) {
  1218. return replace_non_nchw4_opr(opr, new_inp);
  1219. }
  1220. return replace_inps_to_nchw4(opr, new_inp);
  1221. };
  1222. auto replace_resize_opr = [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1223. OperatorNodeBase* opr,
  1224. const VarNodeArray new_inp) {
  1225. using Param = opr::ResizeForward::Param;
  1226. using Format = Param::Format;
  1227. mgb_assert(opr->input().size() == new_inp.size());
  1228. auto& resize = opr->cast_final_safe<opr::ResizeForward>();
  1229. if (resize.param().format != Format::NCHW4) {
  1230. return replace_non_nchw4_opr(opr, new_inp);
  1231. }
  1232. return replace_inps_to_nchw4(opr, new_inp);
  1233. };
  1234. auto replace_pooling_opr = [replace_non_nchw4_opr](
  1235. OperatorNodeBase* opr,
  1236. const VarNodeArray new_inp) {
  1237. using Param = opr::PoolingForward::Param;
  1238. using Format = Param::Format;
  1239. mgb_assert(opr->input().size() == new_inp.size());
  1240. auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
  1241. if (pooling.param().format != Format::NCHW4) {
  1242. return replace_non_nchw4_opr(opr, new_inp);
  1243. }
  1244. size_t nr_inps = opr->input().size();
  1245. MGB_MARK_USED_VAR(nr_inps);
  1246. mgb_assert(nr_inps == 1);
  1247. size_t nr_channels = opr->input(0)->shape()[1] * 4;
  1248. if (nr_channels % 32 == 0) { // use nchw32 format
  1249. VarNode* new_inp_var = new_inp[0];
  1250. if (opr->input(0)->shape().eq_shape(new_inp[0]->shape())) {
  1251. new_inp_var =
  1252. RelayoutPlaceholder::make(
  1253. new_inp[0], RelayoutPlaceholder::LayoutType::
  1254. NCHW4_TO_NCHW32)
  1255. .node();
  1256. } else {
  1257. mgb_assert(opr->input(0)->shape().ndim == 5 &&
  1258. opr->input(0)->shape()[4] == 4);
  1259. mgb_assert(new_inp[0]->shape().ndim == 5 &&
  1260. new_inp[0]->shape()[4] == 32);
  1261. }
  1262. auto new_param = pooling.param();
  1263. new_param.format = Format::NCHW32;
  1264. auto new_pooling = opr::PoolingForward::make(new_inp_var, new_param,
  1265. opr->config());
  1266. return new_pooling.node()->owner_opr();
  1267. }
  1268. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1269. };
  1270. auto ret = std::make_unique<EnableTensorCorePass>();
  1271. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  1272. auto&& replace_func = ret->m_opr_replace_func;
  1273. replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;
  1274. // elemwise like
  1275. replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
  1276. replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
  1277. replace_func[opr::ElemwiseMultiType::typeinfo()] =
  1278. replace_elemwise_like_opr;
  1279. replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;
  1280. // format aware
  1281. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  1282. replace_func[opr::WarpAffineForward::typeinfo()] = replace_warp_affine_opr;
  1283. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  1284. replace_warp_perspective_opr;
  1285. replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
  1286. // to nchw4
  1287. replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw4;
  1288. replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw4;
  1289. replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw4;
  1290. replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw4;
  1291. replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw4;
  1292. return ret;
  1293. MIDOUT_E
  1294. }
  1295. /* ================ EnableCHWN4Pass =============== */
  1296. VarNode* EnableCHWN4Pass::on_graph_endpoint_var(VarNode* new_var,
  1297. VarNode* /* orig_var */) const {
  1298. if (m_varshape_changed.count(new_var)) {
  1299. return RelayoutPlaceholder::make(
  1300. new_var, RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4)
  1301. .node();
  1302. }
  1303. return new_var;
  1304. }
  1305. std::unique_ptr<EnableCHWN4Pass> EnableCHWN4Pass::make_chwn4_converter() {
  1306. MIDOUT_B("EnableCHWN4Pass::make")
  1307. auto ret = std::make_unique<EnableCHWN4Pass>();
  1308. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  1309. auto&& replace_func = ret->m_opr_replace_func;
  1310. auto&& varshape_changed = ret->m_varshape_changed;
  1311. // replace rule for conv bias opr
  1312. auto replace_conv_bias_opr = [&varshape_changed](
  1313. OperatorNodeBase* opr,
  1314. const VarNodeArray& new_inp) {
  1315. using Param = megdnn::param::ConvBias;
  1316. using Format = Param::Format;
  1317. mgb_assert(opr->input().size() == new_inp.size());
  1318. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  1319. if (conv_bias.param().format != Format::NCHW4 ||
  1320. conv_bias.output(0)->dtype().enumv() != DTypeEnum::QuantizedS8) {
  1321. size_t nr_inps = new_inp.size();
  1322. bool shape_has_changed = false;
  1323. for (size_t i = 0; i < nr_inps; ++i) {
  1324. if (varshape_changed.count(new_inp[i])) {
  1325. shape_has_changed = true;
  1326. break;
  1327. }
  1328. }
  1329. mgb_assert(
  1330. !shape_has_changed,
  1331. "EnableCHWN4Pass assumes that the shape of inputs of"
  1332. "ConvBias operators whose output dtype is not QuantizedS8 "
  1333. "can not be changed in this opt pass");
  1334. return serialization::copy_opr_shallow(*opr, new_inp,
  1335. opr->config());
  1336. }
  1337. mgb_assert(varshape_changed.count(new_inp[1]) == 0,
  1338. "EnableCHWN4Pass assumes that filter tensor of "
  1339. "conv_bias operator can not be changed by other operators");
  1340. VarNode *src = nullptr, *weight = nullptr, *bias = nullptr,
  1341. *z_inp = nullptr;
  1342. // process src tensor
  1343. if (varshape_changed.count(new_inp[0]) ==
  1344. 0) { // new input is NCHW4 layout
  1345. // currently not support group conv
  1346. auto symvar = RelayoutPlaceholder::make(
  1347. new_inp[0],
  1348. RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
  1349. src = symvar.node();
  1350. } else { // new input is NCHW32 layout
  1351. src = new_inp[0];
  1352. }
  1353. // process weight tensor
  1354. {
  1355. auto symvar = RelayoutPlaceholder::make(
  1356. new_inp[1],
  1357. RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
  1358. weight = symvar.node();
  1359. }
  1360. if (new_inp.size() == 2) {
  1361. auto param = conv_bias.param();
  1362. param.format = Format::CHWN4;
  1363. auto new_opr = opr::ConvBiasForward::make(
  1364. src, weight, param, conv_bias.execution_policy(),
  1365. conv_bias.config());
  1366. varshape_changed.insert(new_opr.node());
  1367. return new_opr.node()->owner_opr();
  1368. }
  1369. auto process_inp = [&](VarNode* inp) -> VarNode* {
  1370. if (varshape_changed.count(inp) == 0) {
  1371. auto symvar = RelayoutPlaceholder::make(
  1372. inp, RelayoutPlaceholder::LayoutType::NCHW4_TO_CHWN4);
  1373. return symvar.node();
  1374. } else {
  1375. return inp;
  1376. }
  1377. };
  1378. // process bias tensor
  1379. bias = process_inp(new_inp[2]);
  1380. if (new_inp.size() == 3) {
  1381. auto param = conv_bias.param();
  1382. param.format = Format::CHWN4;
  1383. auto new_opr = opr::ConvBiasForward::make(
  1384. src, weight, bias, param, conv_bias.execution_policy(),
  1385. conv_bias.config());
  1386. varshape_changed.insert(new_opr.node());
  1387. return new_opr.node()->owner_opr();
  1388. }
  1389. // process z_inp tensor
  1390. z_inp = process_inp(new_inp[3]);
  1391. auto param = conv_bias.param();
  1392. param.format = Format::CHWN4;
  1393. auto new_opr = opr::ConvBiasForward::make(
  1394. src, weight, bias, z_inp, param, conv_bias.execution_policy(),
  1395. conv_bias.config());
  1396. varshape_changed.insert(new_opr.node());
  1397. return new_opr.node()->owner_opr();
  1398. };
  1399. // replace rule for elemwise like opr
  1400. // for oprs support NCHW4 and CHWN4 layout
  1401. auto replace_elemwise_like_opr = [&varshape_changed](
  1402. OperatorNodeBase* opr,
  1403. const VarNodeArray new_inp) {
  1404. mgb_assert(opr->input().size() == new_inp.size());
  1405. size_t nr_inps = new_inp.size();
  1406. size_t nr_shape_changed = 0;
  1407. for (size_t i = 0; i < nr_inps; ++i) {
  1408. if (varshape_changed.count(new_inp[i])) {
  1409. nr_shape_changed++;
  1410. }
  1411. }
  1412. if (nr_shape_changed) {
  1413. auto inps = new_inp;
  1414. if (nr_shape_changed >=
  1415. nr_inps / 2) { // CHWN4 > NCHW4 -> use CHWN4
  1416. for (size_t i = 0; i < nr_inps; ++i) {
  1417. if (varshape_changed.count(new_inp[i]) == 0) {
  1418. auto symvar = RelayoutPlaceholder::make(
  1419. new_inp[i], RelayoutPlaceholder::LayoutType::
  1420. NCHW4_TO_CHWN4);
  1421. inps[i] = symvar.node();
  1422. }
  1423. }
  1424. auto new_opr = serialization::copy_opr_shallow(*opr, inps,
  1425. opr->config());
  1426. varshape_changed.insert(new_opr->output(0));
  1427. return new_opr;
  1428. } else { // CHWN4 < NCHW4 -> use NCHW4
  1429. for (size_t i = 0; i < nr_inps; ++i) {
  1430. if (varshape_changed.count(new_inp[i])) {
  1431. auto symvar = RelayoutPlaceholder::make(
  1432. new_inp[i], RelayoutPlaceholder::LayoutType::
  1433. CHWN4_TO_NCHW4);
  1434. inps[i] = symvar.node();
  1435. }
  1436. }
  1437. return serialization::copy_opr_shallow(*opr, inps,
  1438. opr->config());
  1439. }
  1440. }
  1441. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1442. };
  1443. // for oprs only supports NCHW4 layout
  1444. auto replace_inps_to_nchw4 = [&varshape_changed](
  1445. OperatorNodeBase* opr,
  1446. const VarNodeArray new_inp) {
  1447. mgb_assert(opr->input().size() == new_inp.size());
  1448. VarNodeArray inps = new_inp;
  1449. for (size_t i = 0; i < opr->input().size(); ++i) {
  1450. if (varshape_changed.count(new_inp[i])) {
  1451. auto symvar = RelayoutPlaceholder::make(
  1452. new_inp[i],
  1453. RelayoutPlaceholder::LayoutType::CHWN4_TO_NCHW4);
  1454. inps[i] = symvar.node();
  1455. }
  1456. }
  1457. auto new_opr =
  1458. serialization::copy_opr_shallow(*opr, inps, opr->config());
  1459. return new_opr;
  1460. };
  1461. auto replace_non_nchw4_opr = [&varshape_changed](
  1462. OperatorNodeBase* opr,
  1463. const VarNodeArray new_inp) {
  1464. size_t nr_inps = opr->input().size();
  1465. bool shape_has_changed = false;
  1466. for (size_t i = 0; i < nr_inps; ++i) {
  1467. if (varshape_changed.count(new_inp[i])) {
  1468. shape_has_changed = true;
  1469. }
  1470. }
  1471. mgb_assert(!shape_has_changed,
  1472. "EnableCHWN4Pass assumes that inputs' shape of "
  1473. "non-nchw4 operators "
  1474. "can not be changed in this opt "
  1475. "pass");
  1476. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1477. };
  1478. // capture by copy to avoid use after return
  1479. auto replace_warp_affine_opr =
  1480. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1481. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1482. using Param = opr::WarpAffineForward::Param;
  1483. using Format = Param::Format;
  1484. mgb_assert(opr->input().size() == new_inp.size());
  1485. auto& warp = opr->cast_final_safe<opr::WarpAffineForward>();
  1486. if (warp.param().format != Format::NCHW4) {
  1487. return replace_non_nchw4_opr(opr, new_inp);
  1488. }
  1489. return replace_inps_to_nchw4(opr, new_inp);
  1490. };
  1491. auto replace_warp_perspective_opr =
  1492. [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1493. OperatorNodeBase* opr, const VarNodeArray new_inp) {
  1494. using Param = opr::WarpPerspectiveForward::Param;
  1495. using Format = Param::Format;
  1496. mgb_assert(opr->input().size() == new_inp.size());
  1497. auto& warp =
  1498. opr->cast_final_safe<opr::WarpPerspectiveForward>();
  1499. if (warp.param().format != Format::NCHW4) {
  1500. return replace_non_nchw4_opr(opr, new_inp);
  1501. }
  1502. return replace_inps_to_nchw4(opr, new_inp);
  1503. };
  1504. auto replace_resize_opr = [replace_inps_to_nchw4, replace_non_nchw4_opr](
  1505. OperatorNodeBase* opr,
  1506. const VarNodeArray new_inp) {
  1507. using Param = opr::ResizeForward::Param;
  1508. using Format = Param::Format;
  1509. mgb_assert(opr->input().size() == new_inp.size());
  1510. auto& resize = opr->cast_final_safe<opr::ResizeForward>();
  1511. if (resize.param().format != Format::NCHW4) {
  1512. return replace_non_nchw4_opr(opr, new_inp);
  1513. }
  1514. return replace_inps_to_nchw4(opr, new_inp);
  1515. };
  1516. auto replace_pooling_opr = [&varshape_changed, replace_non_nchw4_opr](
  1517. OperatorNodeBase* opr,
  1518. const VarNodeArray new_inp) {
  1519. using Param = opr::PoolingForward::Param;
  1520. using Format = Param::Format;
  1521. mgb_assert(opr->input().size() == new_inp.size());
  1522. auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
  1523. if (pooling.param().format != Format::NCHW4) {
  1524. return replace_non_nchw4_opr(opr, new_inp);
  1525. }
  1526. size_t nr_inps = opr->input().size();
  1527. MGB_MARK_USED_VAR(nr_inps);
  1528. mgb_assert(nr_inps == 1);
  1529. if (varshape_changed.count(new_inp[0])) {
  1530. auto new_param = pooling.param();
  1531. new_param.format = Format::CHWN4;
  1532. auto new_pooling = opr::PoolingForward::make(new_inp[0], new_param,
  1533. opr->config());
  1534. varshape_changed.insert(new_pooling.node());
  1535. return new_pooling.node()->owner_opr();
  1536. }
  1537. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1538. };
  1539. replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;
  1540. // elemwise like
  1541. replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
  1542. replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
  1543. replace_func[opr::ElemwiseMultiType::typeinfo()] =
  1544. replace_elemwise_like_opr;
  1545. replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;
  1546. // format aware
  1547. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  1548. replace_func[opr::WarpAffineForward::typeinfo()] = replace_warp_affine_opr;
  1549. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  1550. replace_warp_perspective_opr;
  1551. replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
  1552. // to nchw4
  1553. replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw4;
  1554. replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw4;
  1555. replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw4;
  1556. replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw4;
  1557. replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw4;
  1558. replace_func[opr::BatchConvBias::typeinfo()] = replace_inps_to_nchw4;
  1559. return ret;
  1560. MIDOUT_E
  1561. }
  1562. /* ================ EnableNCHW4Pass ================ */
  1563. VarNode* EnableNCHW4Pass::on_graph_endpoint_var(VarNode* new_var,
  1564. VarNode* orig_var) const {
  1565. if (!orig_var->shape().eq_shape(new_var->shape())) {
  1566. return RelayoutPlaceholder::make(
  1567. new_var, RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
  1568. .node();
  1569. }
  1570. return new_var;
  1571. }
  1572. //! FIXME: All float oprs do not support NCHW4. Supports it in the future plz.
  1573. std::unique_ptr<EnableNCHW4Pass> EnableNCHW4Pass::make_nchw4_converter() {
  1574. MIDOUT_B("EnableNCHW4Pass::make")
  1575. auto ret = std::make_unique<EnableNCHW4Pass>();
  1576. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  1577. using RelayoutMode = RelayoutPlaceholder::LayoutType;
  1578. megdnn::param::Convolution::Format conv_format =
  1579. megdnn::param::Convolution::Format::NCHW4;
  1580. megdnn::param::ConvBias::Format conv_bias_format =
  1581. megdnn::param::ConvBias::Format::NCHW4;
  1582. megdnn::param::ConvBias::Format conv_bias_format_nchw4_nchw =
  1583. megdnn::param::ConvBias::Format::NCHW4_NCHW;
  1584. megdnn::param::BatchConvBias::Format batch_conv_bias_format =
  1585. megdnn::param::BatchConvBias::Format::NCHW4;
  1586. RelayoutMode src_to_nchw4_mode = RelayoutMode::NCHW_TO_NCHW4;
  1587. RelayoutMode src_to_nchw_mode = RelayoutMode::NCHW4_TO_NCHW;
  1588. RelayoutMode weight_to_nchw4_mode_dense =
  1589. RelayoutMode::WEIGHT_NCHW_TO_NCHW4_DENSE;
  1590. RelayoutMode weight_to_nchw4_mode_group =
  1591. RelayoutMode::WEIGHT_NCHW_TO_NCHW4_GROUP;
  1592. struct ConvMode {
  1593. RelayoutMode weight;
  1594. RelayoutMode src;
  1595. };
  1596. auto trans_nchw4 =
  1597. [weight_to_nchw4_mode_dense, weight_to_nchw4_mode_group,
  1598. src_to_nchw4_mode](
  1599. const megdnn::param::Convolution::Sparse conv_mode,
  1600. const VarNode* filter) -> ConvMode {
  1601. if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
  1602. mgb_assert(filter->shape().ndim == 4,
  1603. "The origin filter is not NCHW mode");
  1604. size_t IC = filter->shape()[1];
  1605. if (IC < 4) {
  1606. return {RelayoutMode::WEIGHT_NCHW_TO_NCHW4_DENSE_IC_SMALL_CONV,
  1607. RelayoutMode::NCHW_TO_NCHW4_IC_SMALL_CONV};
  1608. } else {
  1609. return {weight_to_nchw4_mode_dense, src_to_nchw4_mode};
  1610. }
  1611. } else {
  1612. mgb_throw_if(conv_mode != megdnn::param::Convolution::Sparse::GROUP,
  1613. MegBrainError, "mode error");
  1614. mgb_assert(filter->shape().ndim == 5,
  1615. "The origin filter if not NCHW mode");
  1616. size_t IC = filter->shape()[2];
  1617. mgb_assert(IC % 4 == 0,
  1618. "The input channel should be divisible by 4 for group "
  1619. "conv");
  1620. return {weight_to_nchw4_mode_group, src_to_nchw4_mode};
  1621. }
  1622. };
  1623. auto replace_conv_opr = [trans_nchw4, conv_format](
  1624. OperatorNodeBase* opr,
  1625. const VarNodeArray& new_inp) {
  1626. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1627. return serialization::copy_opr_shallow(*opr, new_inp,
  1628. opr->config());
  1629. }
  1630. mgb_assert(opr->input().size() == new_inp.size());
  1631. auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
  1632. if (conv_opr.param().format !=
  1633. megdnn::param::Convolution::Format::NCHW) {
  1634. return serialization::copy_opr_shallow(*opr, new_inp,
  1635. opr->config());
  1636. }
  1637. auto conv_mode = trans_nchw4(conv_opr.param().sparse, new_inp[1]);
  1638. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  1639. // src: NCHW --> NCWH4
  1640. if (new_inp[0]->shape().ndim != 5) {
  1641. mgb_assert(new_inp[0]->shape().ndim == 4);
  1642. auto new_src = RelayoutPlaceholder::make(new_inp[0], conv_mode.src);
  1643. conv_src = new_src.node();
  1644. }
  1645. // weight: NCHW --> NCHW4
  1646. auto new_filter =
  1647. RelayoutPlaceholder::make(new_inp[1], conv_mode.weight);
  1648. conv_filter = new_filter.node();
  1649. // format: NCHW --> NCHW4
  1650. auto new_param = conv_opr.param();
  1651. new_param.format = conv_format;
  1652. // dst
  1653. auto new_conv_opr = opr::Convolution::make(
  1654. conv_src, conv_filter, new_param, conv_opr.execution_policy(),
  1655. conv_opr.config());
  1656. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  1657. mgb_assert(new_conv_opr.shape().ndim == 5,
  1658. "The conv dst dim is not trans to nchw4");
  1659. return new_opr;
  1660. };
  1661. auto replace_deconv_opr = [trans_nchw4, conv_format](
  1662. OperatorNodeBase* opr,
  1663. const VarNodeArray& new_inp) {
  1664. if (new_inp[1]->dtype().enumv() == DTypeEnum::Float32) {
  1665. return serialization::copy_opr_shallow(*opr, new_inp,
  1666. opr->config());
  1667. }
  1668. mgb_assert(opr->input().size() == new_inp.size());
  1669. auto& deconv_opr = opr->cast_final_safe<opr::ConvolutionBackwardData>();
  1670. if ((deconv_opr.param().format !=
  1671. megdnn::param::Convolution::Format::NCHW) ||
  1672. (deconv_opr.param().sparse !=
  1673. megdnn::param::Convolution::Sparse::DENSE)) {
  1674. return serialization::copy_opr_shallow(*opr, new_inp,
  1675. opr->config());
  1676. }
  1677. VarNode *deconv_src = new_inp[1], *deconv_filter = new_inp[0];
  1678. auto deconv_mode = trans_nchw4(deconv_opr.param().sparse, deconv_filter);
  1679. // src: NCHW --> NCWH4
  1680. if (deconv_src->shape().ndim != 5) {
  1681. mgb_assert(deconv_src->shape().ndim == 4);
  1682. auto new_src =
  1683. RelayoutPlaceholder::make(deconv_src, deconv_mode.src);
  1684. deconv_src = new_src.node();
  1685. }
  1686. // weight: NCHW --> NCHW4
  1687. auto new_filter =
  1688. RelayoutPlaceholder::make(deconv_filter, deconv_mode.weight);
  1689. deconv_filter = new_filter.node();
  1690. // format: NCHW --> NCHW4
  1691. auto new_param = deconv_opr.param();
  1692. new_param.format = conv_format;
  1693. // dst
  1694. auto new_deconv_opr = opr::ConvolutionBackwardData::make_deconv(
  1695. deconv_src, deconv_filter, new_param,
  1696. deconv_opr.execution_policy(), deconv_opr.config());
  1697. OperatorNodeBase* new_opr = new_deconv_opr.node()->owner_opr();
  1698. return new_opr;
  1699. };
  1700. auto replace_batch_conv_bias_opr = [batch_conv_bias_format,
  1701. src_to_nchw4_mode](
  1702. OperatorNodeBase* opr,
  1703. const VarNodeArray& new_inp) {
  1704. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1705. return serialization::copy_opr_shallow(*opr, new_inp,
  1706. opr->config());
  1707. }
  1708. mgb_assert(opr->input().size() == new_inp.size());
  1709. auto& batch_conv_bias_opr =
  1710. opr->cast_final_safe<opr::BatchConvBiasForward>();
  1711. if (batch_conv_bias_opr.param().format !=
  1712. megdnn::param::BatchConvBias::Format::NCHW) {
  1713. return serialization::copy_opr_shallow(*opr, new_inp,
  1714. opr->config());
  1715. }
  1716. mgb_assert(batch_conv_bias_opr.param().format ==
  1717. megdnn::param::BatchConvBias::Format::NCHW,
  1718. "ConvertFormat Pass only support converting NCHW to NCHW4");
  1719. // what should be converted: src, weight
  1720. VarNode *src = new_inp[0], *filter = new_inp[1];
  1721. // src: NCHW --> NCHW4
  1722. if (new_inp[0]->shape().ndim != 5) {
  1723. mgb_assert(new_inp[0]->shape().ndim == 4);
  1724. auto new_src =
  1725. RelayoutPlaceholder::make(new_inp[0], src_to_nchw4_mode);
  1726. src = new_src.node();
  1727. }
  1728. // weight: BNCHW --> BNCHW4
  1729. // only support dense mode, which is similar with conv->group.
  1730. auto weight_mode =
  1731. RelayoutPlaceholder::LayoutType::WEIGHT_NCHW_TO_NCHW4_GROUP;
  1732. auto new_filter = RelayoutPlaceholder::make(new_inp[1], weight_mode);
  1733. filter = new_filter.node();
  1734. // format: NCHW --> NCHW4
  1735. auto new_param = batch_conv_bias_opr.param();
  1736. new_param.format = batch_conv_bias_format;
  1737. if (new_inp.size() == 2) {
  1738. auto dst = opr::BatchConvBias::make(
  1739. src, filter, new_param,
  1740. batch_conv_bias_opr.execution_policy(),
  1741. batch_conv_bias_opr.config());
  1742. OperatorNodeBase* new_opr = dst.node()->owner_opr();
  1743. mgb_assert(dst.shape().ndim == 5,
  1744. "The conv_bias dst dim is not trans to nchw4");
  1745. return new_opr;
  1746. }
  1747. // bias: NCHW --> NCHW4
  1748. VarNode* bias = new_inp[2];
  1749. if (new_inp[2]->shape().ndim == 4) {
  1750. auto new_bias =
  1751. RelayoutPlaceholder::make(new_inp[2], src_to_nchw4_mode);
  1752. bias = new_bias.node();
  1753. }
  1754. if (new_inp.size() == 3) {
  1755. auto dst = opr::BatchConvBias::make(
  1756. src, filter, bias, new_param,
  1757. batch_conv_bias_opr.execution_policy(),
  1758. batch_conv_bias_opr.config());
  1759. OperatorNodeBase* new_opr = dst.node()->owner_opr();
  1760. mgb_assert(dst.shape().ndim == 5,
  1761. "The conv_bias dst dim is not trans to nchw4");
  1762. return new_opr;
  1763. }
  1764. // z_inp: NCHW --> NCHW4
  1765. VarNode* z_inp = new_inp[3];
  1766. if (new_inp[3]->shape().ndim == 4) {
  1767. auto new_z =
  1768. RelayoutPlaceholder::make(new_inp[3], src_to_nchw4_mode);
  1769. z_inp = new_z.node();
  1770. }
  1771. auto dst =
  1772. opr::BatchConvBias::make(src, filter, bias, z_inp, new_param,
  1773. batch_conv_bias_opr.execution_policy(),
  1774. batch_conv_bias_opr.config());
  1775. OperatorNodeBase* new_opr = dst.node()->owner_opr();
  1776. mgb_assert(dst.shape().ndim == 5,
  1777. "The conv_bias dst dim is not trans to nchw4");
  1778. return new_opr;
  1779. };
  1780. auto replace_conv_bias_opr = [trans_nchw4, conv_bias_format,
  1781. conv_bias_format_nchw4_nchw,
  1782. src_to_nchw4_mode](
  1783. OperatorNodeBase* opr,
  1784. const VarNodeArray& new_inp) {
  1785. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1786. return serialization::copy_opr_shallow(*opr, new_inp,
  1787. opr->config());
  1788. }
  1789. mgb_assert(opr->input().size() == new_inp.size());
  1790. auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
  1791. if (conv_bias_opr.param().format !=
  1792. megdnn::param::Convolution::Format::NCHW) {
  1793. return serialization::copy_opr_shallow(*opr, new_inp,
  1794. opr->config());
  1795. }
  1796. // what should be converted: src, weight
  1797. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1];
  1798. auto conv_mode = trans_nchw4(conv_bias_opr.param().sparse, new_inp[1]);
  1799. // src: NCHW --> NCHW4
  1800. if (new_inp[0]->shape().ndim != 5) {
  1801. mgb_assert(new_inp[0]->shape().ndim == 4);
  1802. auto new_src = RelayoutPlaceholder::make(new_inp[0], conv_mode.src);
  1803. conv_bias_src = new_src.node();
  1804. }
  1805. // weight: NCHW --> NCHW4 or GNCHW --> GNCHW4
  1806. auto new_filter =
  1807. RelayoutPlaceholder::make(new_inp[1], conv_mode.weight);
  1808. conv_bias_filter = new_filter.node();
  1809. // format: NCHW --> NCHW4
  1810. auto new_param = conv_bias_opr.param();
  1811. if (conv_bias_opr.output().size() > 0 &&
  1812. conv_bias_opr.output(0)->dtype().enumv() == DTypeEnum::Float32) {
  1813. new_param.format = conv_bias_format_nchw4_nchw;
  1814. } else {
  1815. new_param.format = conv_bias_format;
  1816. }
  1817. if (new_inp.size() == 2) {
  1818. auto new_conv_bias_opr = opr::ConvBias::make(
  1819. conv_bias_src, conv_bias_filter, new_param,
  1820. conv_bias_opr.execution_policy(), conv_bias_opr.config());
  1821. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  1822. mgb_assert(
  1823. new_conv_bias_opr.node()->dtype().enumv() == DTypeEnum::Float32 ||
  1824. new_conv_bias_opr.shape().ndim == 5,
  1825. "The conv_bias dst dim is not trans to nchw4");
  1826. return new_opr;
  1827. }
  1828. // bias: NCHW --> NCHW4 when bias_dtype is not Float32
  1829. VarNode* conv_bias_bias = new_inp[2];
  1830. if (new_inp[2]->dtype().enumv() != DTypeEnum::Float32 &&
  1831. new_inp[2]->shape().ndim == 4) {
  1832. auto new_bias =
  1833. RelayoutPlaceholder::make(new_inp[2], src_to_nchw4_mode);
  1834. conv_bias_bias = new_bias.node();
  1835. }
  1836. if (new_inp.size() == 3) {
  1837. auto new_conv_bias_opr = opr::ConvBias::make(
  1838. conv_bias_src, conv_bias_filter, conv_bias_bias, new_param,
  1839. conv_bias_opr.execution_policy(), conv_bias_opr.config());
  1840. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  1841. mgb_assert(
  1842. new_conv_bias_opr.node()->dtype().enumv() == DTypeEnum::Float32 ||
  1843. new_conv_bias_opr.shape().ndim == 5,
  1844. "The conv_bias dst dim is not trans to nchw4");
  1845. return new_opr;
  1846. }
  1847. // z_inp: NCHW --> NCHW4 when bias_dtype is not Float32
  1848. VarNode* z_inp = new_inp[3];
  1849. if (new_inp[3]->dtype().enumv() != DTypeEnum::Float32 &&
  1850. new_inp[3]->shape().ndim == 4) {
  1851. auto new_z =
  1852. RelayoutPlaceholder::make(new_inp[3], src_to_nchw4_mode);
  1853. z_inp = new_z.node();
  1854. }
  1855. auto new_conv_bias_opr = opr::ConvBias::make(
  1856. conv_bias_src, conv_bias_filter, conv_bias_bias, z_inp,
  1857. new_param, conv_bias_opr.execution_policy(),
  1858. conv_bias_opr.config());
  1859. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  1860. mgb_assert(
  1861. new_conv_bias_opr.node()->dtype().enumv() == DTypeEnum::Float32 ||
  1862. new_conv_bias_opr.shape().ndim == 5,
  1863. "The conv_bias dst dim is not trans to nchw4");
  1864. return new_opr;
  1865. };
  1866. auto replace_elemwise_opr = [=](OperatorNodeBase* opr,
  1867. const VarNodeArray& new_inp) {
  1868. mgb_assert(opr->input().size() == new_inp.size());
  1869. bool has_inp_changed = false;
  1870. for (size_t i = 0; i < opr->input().size(); i++) {
  1871. if (new_inp[i]->shape().ndim == 5) {
  1872. has_inp_changed = true;
  1873. break;
  1874. }
  1875. }
  1876. if (has_inp_changed) {
  1877. auto temp_inp = new_inp;
  1878. for (size_t i = 0; i < opr->input().size(); i++) {
  1879. if (new_inp[i]->shape().ndim == 4) {
  1880. auto new_var = RelayoutPlaceholder::make(new_inp[i],
  1881. src_to_nchw4_mode);
  1882. temp_inp[i] = new_var.node();
  1883. } else {
  1884. mgb_assert((new_inp[i]->shape().ndim == 5) ||
  1885. new_inp[i]->shape().is_scalar());
  1886. }
  1887. }
  1888. return serialization::copy_opr_shallow(*opr, temp_inp,
  1889. opr->config());
  1890. } else {
  1891. return serialization::copy_opr_shallow(*opr, new_inp,
  1892. opr->config());
  1893. }
  1894. };
  1895. auto relayout_inp_to_nchw = [=](OperatorNodeBase* opr,
  1896. const VarNodeArray& new_inp) {
  1897. mgb_assert(opr->input().size() == new_inp.size());
  1898. VarNodeArray temp_inp = new_inp;
  1899. for (size_t i = 0; i < opr->input().size(); i++) {
  1900. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  1901. mgb_assert(opr->input(i)->shape().ndim == 4);
  1902. mgb_assert(new_inp[i]->shape().ndim == 5);
  1903. auto new_var =
  1904. RelayoutPlaceholder::make(new_inp[i], src_to_nchw_mode);
  1905. temp_inp[i] = new_var.node();
  1906. }
  1907. }
  1908. return serialization::copy_opr_shallow(*opr, temp_inp, opr->config());
  1909. };
  1910. auto replace_pooling_opr = [](OperatorNodeBase* opr,
  1911. const VarNodeArray& new_inp) {
  1912. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1913. return serialization::copy_opr_shallow(*opr, new_inp,
  1914. opr->config());
  1915. }
  1916. using Param = opr::PoolingForward::Param;
  1917. using Format = Param::Format;
  1918. mgb_assert(opr->input().size() == new_inp.size());
  1919. auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
  1920. if (pooling.param().format != Format::NCHW) {
  1921. return opr;
  1922. }
  1923. if (new_inp[0]->shape().ndim == 5) {
  1924. mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
  1925. auto new_param = pooling.param();
  1926. new_param.format = Format::NCHW4;
  1927. auto new_pooling = opr::PoolingForward::make(new_inp[0], new_param,
  1928. opr->config());
  1929. mgb_assert(new_pooling.shape().ndim == 5,
  1930. "out var of Pooling opr after transform must be 5 (got: "
  1931. "%zu).",
  1932. new_pooling.shape().ndim);
  1933. return new_pooling.node()->owner_opr();
  1934. }
  1935. auto new_opr =
  1936. serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1937. return new_opr;
  1938. };
  1939. auto replace_resize_opr = [](OperatorNodeBase* opr,
  1940. const VarNodeArray& new_inp) {
  1941. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1942. return serialization::copy_opr_shallow(*opr, new_inp,
  1943. opr->config());
  1944. }
  1945. using Param = opr::ResizeForward::Param;
  1946. using Format = Param::Format;
  1947. mgb_assert(opr->input().size() == new_inp.size());
  1948. auto& resize = opr->cast_final_safe<opr::ResizeForward>();
  1949. if (new_inp[0]->shape().ndim == 5) {
  1950. mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
  1951. auto new_param = resize.param();
  1952. new_param.format = Format::NCHW4;
  1953. auto new_resize = opr::ResizeForward::make(
  1954. new_inp[0], new_inp[1], new_param, opr->config());
  1955. mgb_assert(new_resize.shape().ndim == 5,
  1956. "out var of Resize opr after transform must be 5 (got: "
  1957. "%zu).",
  1958. new_resize.shape().ndim);
  1959. return new_resize.node()->owner_opr();
  1960. }
  1961. auto new_opr =
  1962. serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1963. return new_opr;
  1964. };
  1965. auto replace_warp_perspective_opr = [](OperatorNodeBase* opr,
  1966. const VarNodeArray& new_inp) {
  1967. if (new_inp[0]->dtype().enumv() == DTypeEnum::Float32) {
  1968. return serialization::copy_opr_shallow(*opr, new_inp,
  1969. opr->config());
  1970. }
  1971. using Param = opr::WarpPerspective::Param;
  1972. using Format = Param::Format;
  1973. mgb_assert(opr->input().size() == new_inp.size());
  1974. auto& warp = opr->cast_final_safe<opr::WarpPerspectiveForward>();
  1975. if (new_inp[0]->shape().ndim == 5) {
  1976. mgb_assert(new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8);
  1977. auto new_param = warp.param();
  1978. new_param.format = Format::NCHW4;
  1979. SymbolVar new_warp;
  1980. if (new_inp.size() == 3) {
  1981. new_warp = opr::WarpPerspectiveForward::make(
  1982. new_inp[0], new_inp[1], nullptr, new_inp[2], new_param,
  1983. opr->config());
  1984. } else {
  1985. mgb_assert(new_inp.size() == 4);
  1986. new_warp = opr::WarpPerspectiveForward::make(
  1987. new_inp[0], new_inp[1], new_inp[2], new_inp[3],
  1988. new_param, opr->config());
  1989. }
  1990. mgb_assert(new_warp.shape().ndim == 5,
  1991. "out var of WarpPerspective opr after transform must be "
  1992. "5 (got: "
  1993. "%zu).",
  1994. new_warp.shape().ndim);
  1995. return new_warp.node()->owner_opr();
  1996. }
  1997. auto new_opr =
  1998. serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  1999. return new_opr;
  2000. };
  2001. auto&& replace_func = ret->m_opr_replace_func;
  2002. //! supportted nchw4
  2003. replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
  2004. replace_func[opr::ConvolutionBackwardData::typeinfo()] =
  2005. replace_deconv_opr;
  2006. replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
  2007. replace_func[opr::BatchConvBias::typeinfo()] = replace_batch_conv_bias_opr;
  2008. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  2009. replace_func[opr::ResizeForward::typeinfo()] = replace_resize_opr;
  2010. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  2011. replace_warp_perspective_opr;
  2012. replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_opr;
  2013. replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_opr;
  2014. replace_func[opr::ElemwiseMultiType::typeinfo()] = replace_elemwise_opr;
  2015. replace_func[opr::PowC::typeinfo()] = replace_elemwise_opr;
  2016. //! not supported nchw4
  2017. replace_func[opr::Concat::typeinfo()] = relayout_inp_to_nchw;
  2018. replace_func[opr::Subtensor::typeinfo()] = relayout_inp_to_nchw;
  2019. replace_func[opr::GetVarShape::typeinfo()] = relayout_inp_to_nchw;
  2020. replace_func[opr::Dimshuffle::typeinfo()] = relayout_inp_to_nchw;
  2021. replace_func[opr::Reduce::typeinfo()] = relayout_inp_to_nchw;
  2022. replace_func[opr::AssertEqual::typeinfo()] = relayout_inp_to_nchw;
  2023. replace_func[opr::IncrSubtensor::typeinfo()] = relayout_inp_to_nchw;
  2024. replace_func[opr::WarpAffineForward::typeinfo()] = relayout_inp_to_nchw;
  2025. return ret;
  2026. MIDOUT_E
  2027. }
  2028. /* ================ EnableNchwxxPass =============== */
  2029. VarNode* EnableNchwxxPass::on_graph_endpoint_var(VarNode* new_var,
  2030. VarNode* orig_var) const {
  2031. if (!orig_var->shape().eq_shape(new_var->shape())) {
  2032. if (m_pack_c_size == 8) {
  2033. return RelayoutPlaceholder::make(
  2034. new_var,
  2035. RelayoutPlaceholder::LayoutType::NCHW88_TO_NCHW)
  2036. .node();
  2037. } else if (m_pack_c_size == 4) {
  2038. return RelayoutPlaceholder::make(
  2039. new_var,
  2040. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
  2041. .node();
  2042. }
  2043. }
  2044. return new_var;
  2045. }
  2046. static inline TensorShape nchwxx_shape_2_nchw_shape(
  2047. const TensorShape& origin_shape) {
  2048. mgb_assert(origin_shape.ndim == 5);
  2049. TensorShape result = origin_shape;
  2050. result[1] *= result[4];
  2051. result.ndim = 4;
  2052. return result;
  2053. }
  2054. template <typename OprType>
  2055. static inline bool nchw_nchwxx_valid(
  2056. const OprType& opr, const VarNodeArray& new_inp, const size_t pack_size,
  2057. megdnn::param::ConvBias::NonlineMode nonline_mode =
  2058. megdnn::param::ConvBias::NonlineMode::IDENTITY,
  2059. bool is_dot = false) {
  2060. auto& src_node = new_inp[0];
  2061. auto& filter_node = new_inp[1];
  2062. auto dst_node = opr.output(0);
  2063. //! already transformed or have fuse Z
  2064. if (filter_node->shape().ndim != 4 || new_inp.size() == 4) {
  2065. return false;
  2066. }
  2067. megdnn::ConvolutionBase<megdnn::param::Convolution>::CanonizedFilterMeta fm;
  2068. fm.format = megdnn::param::Convolution::Format::NCHW;
  2069. fm.should_flip =
  2070. opr.param().mode == megdnn::ConvBiasForward::Mode::CONVOLUTION;
  2071. fm.group = 1;
  2072. fm.spatial_ndim = 2;
  2073. fm.ocpg = filter_node->shape()[0];
  2074. fm.icpg = filter_node->shape()[1];
  2075. fm.spatial[0] = filter_node->shape()[2];
  2076. fm.spatial[1] = filter_node->shape()[3];
  2077. fm.stride[0] = opr.param().stride_h;
  2078. fm.stride[1] = opr.param().stride_w;
  2079. fm.padding[0] = opr.param().pad_h;
  2080. fm.padding[1] = opr.param().pad_w;
  2081. fm.dilation[0] = opr.param().dilate_h;
  2082. fm.dilation[1] = opr.param().dilate_w;
  2083. megdnn::ConvBiasForward::BiasMode bias_mode =
  2084. megdnn::ConvBiasForward::BiasMode::NO_BIAS;
  2085. if (std::is_same<OprType, opr::ConvBiasForward>::value &&
  2086. new_inp.size() > 2) {
  2087. TensorShape bias_shape = new_inp[2]->shape();
  2088. if (bias_shape.ndim == 5) {
  2089. bias_shape = nchwxx_shape_2_nchw_shape(bias_shape);
  2090. }
  2091. if (bias_shape.ndim == 0) {
  2092. bias_mode = megdnn::ConvBiasForward::BiasMode::NO_BIAS;
  2093. } else if (bias_shape.eq_shape(dst_node->shape())) {
  2094. bias_mode = megdnn::ConvBiasForward::BiasMode::BIAS;
  2095. } else {
  2096. //! just check the ndim, the detail shape check is in check_exec
  2097. mgb_assert(bias_shape.ndim == dst_node->shape().ndim);
  2098. bias_mode =
  2099. megdnn::ConvBiasForward::BiasMode::BROADCAST_CHANNEL_BIAS;
  2100. }
  2101. }
  2102. if (pack_size == 4) {
  2103. if (is_dot && filter_node->dtype().enumv() == DTypeEnum::QuantizedS8) {
  2104. fm.format = megdnn::param::Convolution::Format::NCHW44_DOT;
  2105. } else {
  2106. fm.format = megdnn::param::Convolution::Format::NCHW44;
  2107. }
  2108. } else if (pack_size == 8) {
  2109. fm.format = megdnn::param::Convolution::Format::NCHW88;
  2110. } else {
  2111. mgb_assert(0, "only support nchw44 nchw88");
  2112. }
  2113. return megdnn::ConvBiasForward::is_nchw_nchwxx_optimized(
  2114. src_node->dtype().enumv(), filter_node->dtype().enumv(),
  2115. dst_node->dtype().enumv(), fm, bias_mode, nonline_mode);
  2116. }
  2117. void EnableNchwxxPass::fill_opr_convert_fun(size_t pack_c_size) {
  2118. using RelayoutMode = RelayoutPlaceholder::LayoutType;
  2119. using TestFilterResult = std::pair<TransType, RelayoutMode>;
  2120. RelayoutMode weight_to_nchwxx_mode_dense =
  2121. RelayoutMode::WEIGHT_NCHW_TO_NCHW88_DENSE;
  2122. RelayoutMode weight_to_nchwxx_mode_group =
  2123. RelayoutMode::WEIGHT_NCHW_TO_NCHW88_GROUP;
  2124. RelayoutMode weight_to_nchwxx_mode_chan =
  2125. RelayoutMode::WEIGHT_NCHW_TO_NCHW88_CHAN;
  2126. RelayoutMode hybrid_nchw_nchwxx = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW88;
  2127. RelayoutMode src_to_nchwxx_mode = RelayoutMode::NCHW_TO_NCHW88;
  2128. RelayoutMode src_to_nchw_mode = RelayoutMode::NCHW88_TO_NCHW;
  2129. megdnn::param::ConvBias::Format conv_bias_format =
  2130. megdnn::param::ConvBias::Format::NCHW88;
  2131. megdnn::param::Convolution::Format conv_format =
  2132. megdnn::param::Convolution::Format::NCHW88;
  2133. megdnn::param::Pooling::Format pooling_format =
  2134. megdnn::param::Pooling::Format::NCHW88;
  2135. std::string convter_pass_name = "conv_format_nchw88";
  2136. if (pack_c_size == 4) {
  2137. weight_to_nchwxx_mode_dense = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DENSE;
  2138. weight_to_nchwxx_mode_group = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_GROUP;
  2139. weight_to_nchwxx_mode_chan = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_CHAN;
  2140. hybrid_nchw_nchwxx = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW44;
  2141. src_to_nchwxx_mode = RelayoutMode::NCHW_TO_NCHW4;
  2142. src_to_nchw_mode = RelayoutMode::NCHW4_TO_NCHW;
  2143. conv_bias_format = megdnn::param::ConvBias::Format::NCHW44;
  2144. conv_format = megdnn::param::Convolution::Format::NCHW44;
  2145. pooling_format = megdnn::param::Pooling::Format::NCHW44;
  2146. convter_pass_name = "conv_format_nchw44";
  2147. }
  2148. auto test_trans_nchwxx =
  2149. [pack_c_size, weight_to_nchwxx_mode_dense,
  2150. weight_to_nchwxx_mode_group, weight_to_nchwxx_mode_chan,
  2151. hybrid_nchw_nchwxx](
  2152. const megdnn::param::Convolution::Sparse conv_mode,
  2153. const VarNode* filter, const size_t stride_h,
  2154. const size_t stride_w,
  2155. bool valid_nchw_nchw44) -> TestFilterResult {
  2156. TestFilterResult ret{TransType::TRANS_NONE, {}};
  2157. if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
  2158. size_t OC = filter->shape()[0];
  2159. size_t IC = filter->shape()[1];
  2160. if ((IC % pack_c_size == 0) && (OC % pack_c_size == 0)) {
  2161. ret.first = TransType::TRANS_PURE_NCHWXX;
  2162. ret.second = weight_to_nchwxx_mode_dense;
  2163. } else if (valid_nchw_nchw44) {
  2164. ret.first = TransType::TRANS_HYBIRD_NCHWXX;
  2165. ret.second = hybrid_nchw_nchwxx;
  2166. }
  2167. } else {
  2168. mgb_throw_if(conv_mode != megdnn::param::Convolution::Sparse::GROUP,
  2169. MegBrainError, "mode error");
  2170. size_t group = filter->shape()[0];
  2171. size_t ocpg = filter->shape()[1];
  2172. size_t icpg = filter->shape()[2];
  2173. if (icpg == 1 && ocpg == 1 && (group % pack_c_size == 0)) {
  2174. ret.first = TransType::TRANS_PURE_NCHWXX;
  2175. ret.second = weight_to_nchwxx_mode_chan;
  2176. } else if ((icpg % pack_c_size == 0) && (ocpg % pack_c_size == 0)) {
  2177. ret.first = TransType::TRANS_PURE_NCHWXX;
  2178. ret.second = weight_to_nchwxx_mode_group;
  2179. }
  2180. }
  2181. return ret;
  2182. };
  2183. auto replace_conv_opr = [test_trans_nchwxx, conv_format, src_to_nchwxx_mode,
  2184. src_to_nchw_mode,
  2185. pack_c_size](OperatorNodeBase* opr,
  2186. const VarNodeArray& new_inp) {
  2187. mgb_assert(opr->input().size() == new_inp.size());
  2188. auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
  2189. mgb_throw_if(
  2190. conv_opr.param().format !=
  2191. megdnn::param::Convolution::Format::NCHW,
  2192. MegBrainError,
  2193. "ConvertFormat Pass only support converting NCHW to NCHWXX");
  2194. bool valid_nchw_nchw44 =
  2195. nchw_nchwxx_valid(conv_opr, new_inp, pack_c_size);
  2196. auto is_trans = test_trans_nchwxx(
  2197. conv_opr.param().sparse, new_inp[1], conv_opr.param().stride_h,
  2198. conv_opr.param().stride_w, valid_nchw_nchw44);
  2199. //! can not trans to nchwxx
  2200. if (is_trans.first == TransType::TRANS_NONE) {
  2201. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2202. new_inp[1]->shape().ndim == 5,
  2203. "The origin filter is not NCHW mode");
  2204. VarNodeArray temp_inp = new_inp;
  2205. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  2206. if (temp_inp[0]->shape().ndim == 5) {
  2207. auto new_src =
  2208. RelayoutPlaceholder::make(new_inp[0], src_to_nchw_mode);
  2209. temp_inp[0] = new_src.node();
  2210. }
  2211. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  2212. opr->config());
  2213. return new_opr;
  2214. } else if (is_trans.first == TransType::TRANS_PURE_NCHWXX) {
  2215. //! filter trans to nchwxx mode
  2216. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2217. new_inp[1]->shape().ndim == 5,
  2218. "The origin filter is not NCHW mode");
  2219. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  2220. auto new_filter =
  2221. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  2222. conv_filter = new_filter.node();
  2223. //! src trans to nchwxx mode
  2224. if (new_inp[0]->shape().ndim != 5) {
  2225. mgb_assert(new_inp[0]->shape().ndim == 4);
  2226. auto new_src = RelayoutPlaceholder::make(new_inp[0],
  2227. src_to_nchwxx_mode);
  2228. conv_src = new_src.node();
  2229. }
  2230. auto new_param = conv_opr.param();
  2231. new_param.format = conv_format;
  2232. mgb_assert(conv_src->shape().ndim == 5 &&
  2233. conv_filter->shape().ndim >= 6,
  2234. "The conv src dim is not trans to nchwxx");
  2235. auto new_conv_opr = opr::Convolution::make(
  2236. conv_src, conv_filter, new_param,
  2237. conv_opr.execution_policy(), conv_opr.config());
  2238. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  2239. mgb_assert(new_conv_opr.shape().ndim == 5,
  2240. "The conv dst dim is not trans to nchwxx");
  2241. return new_opr;
  2242. } else {
  2243. mgb_assert(is_trans.first == TransType::TRANS_HYBIRD_NCHWXX);
  2244. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  2245. auto new_filter =
  2246. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  2247. conv_filter = new_filter.node();
  2248. mgb_assert(conv_src->shape().ndim == 4 &&
  2249. conv_filter->shape().ndim == 5,
  2250. "The src and filter is OK");
  2251. auto new_param = conv_opr.param();
  2252. new_param.format = conv_format;
  2253. auto new_conv_opr = opr::Convolution::make(
  2254. conv_src, conv_filter, new_param,
  2255. conv_opr.execution_policy(), conv_opr.config());
  2256. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  2257. mgb_assert(new_conv_opr.shape().ndim == 5,
  2258. "The conv dst dim is not trans to nchwxx");
  2259. return new_opr;
  2260. }
  2261. };
  2262. auto replace_conv_bias_opr = [test_trans_nchwxx, conv_bias_format,
  2263. src_to_nchwxx_mode, src_to_nchw_mode,
  2264. pack_c_size](OperatorNodeBase* opr,
  2265. const VarNodeArray& new_inp) {
  2266. mgb_assert(opr->input().size() == new_inp.size());
  2267. mgb_assert(opr->input().size() <= 3,
  2268. "nchwxx does not support conv_bias fuse Z right now");
  2269. auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
  2270. mgb_throw_if(
  2271. conv_bias_opr.param().format !=
  2272. megdnn::param::ConvBias::Format::NCHW,
  2273. MegBrainError,
  2274. "ConvertFormat Pass only support converting NCHW to NCHWXX");
  2275. bool valid_nchw_nchw44 =
  2276. nchw_nchwxx_valid(conv_bias_opr, new_inp, pack_c_size,
  2277. conv_bias_opr.param().nonlineMode);
  2278. auto is_trans = test_trans_nchwxx(
  2279. conv_bias_opr.param().sparse, new_inp[1],
  2280. conv_bias_opr.param().stride_h, conv_bias_opr.param().stride_w,
  2281. valid_nchw_nchw44);
  2282. //! can not trans to nchwxx
  2283. if (is_trans.first == TransType::TRANS_NONE) {
  2284. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2285. new_inp[1]->shape().ndim == 5,
  2286. "The origin filter is not NCHW mode");
  2287. VarNodeArray temp_inp = new_inp;
  2288. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  2289. if (temp_inp[0]->shape().ndim == 5) {
  2290. auto new_src =
  2291. RelayoutPlaceholder::make(new_inp[0], src_to_nchw_mode);
  2292. temp_inp[0] = new_src.node();
  2293. }
  2294. //! the bias is nchwxx
  2295. if (new_inp.size() > 2 && temp_inp[2]->shape().ndim == 5) {
  2296. auto new_bias =
  2297. RelayoutPlaceholder::make(new_inp[2], src_to_nchw_mode);
  2298. temp_inp[2] = new_bias.node();
  2299. }
  2300. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  2301. opr->config());
  2302. return new_opr;
  2303. } else if (is_trans.first == TransType::TRANS_PURE_NCHWXX) {
  2304. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2305. *conv_bias_bias = nullptr;
  2306. //! filter trans to nchwxx mode
  2307. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2308. new_inp[1]->shape().ndim == 5,
  2309. "The origin filter is not NCHW mode");
  2310. auto new_filter =
  2311. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  2312. conv_bias_filter = new_filter.node();
  2313. //! src trans to nchwxx mode
  2314. if (new_inp[0]->shape().ndim != 5) {
  2315. mgb_assert(new_inp[0]->shape().ndim == 4);
  2316. auto new_src = RelayoutPlaceholder::make(new_inp[0],
  2317. src_to_nchwxx_mode);
  2318. conv_bias_src = new_src.node();
  2319. }
  2320. //! bias trans to nchwxx mode
  2321. if (new_inp.size() > 2) {
  2322. if (new_inp[2]->shape().ndim == 4) {
  2323. auto new_bias = RelayoutPlaceholder::make(
  2324. new_inp[2], src_to_nchwxx_mode);
  2325. conv_bias_bias = new_bias.node();
  2326. } else {
  2327. mgb_assert(new_inp[2]->shape().ndim == 5);
  2328. conv_bias_bias = new_inp[2];
  2329. }
  2330. }
  2331. auto new_param = conv_bias_opr.param();
  2332. new_param.format = conv_bias_format;
  2333. mgb_assert(conv_bias_src->shape().ndim == 5 &&
  2334. conv_bias_filter->shape().ndim >= 6,
  2335. "The conv_bias src dim is not trans to nchwxx");
  2336. SymbolVar new_conv_bias_opr;
  2337. if (conv_bias_bias) {
  2338. new_conv_bias_opr = opr::ConvBias::make(
  2339. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2340. new_param, conv_bias_opr.execution_policy(),
  2341. conv_bias_opr.config());
  2342. } else {
  2343. new_conv_bias_opr = opr::ConvBias::make(
  2344. conv_bias_src, conv_bias_filter, new_param,
  2345. conv_bias_opr.execution_policy(),
  2346. conv_bias_opr.config());
  2347. }
  2348. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2349. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2350. "The conv_bias dst dim is not trans to nchwxx");
  2351. return new_opr;
  2352. } else {
  2353. mgb_assert(is_trans.first == TransType::TRANS_HYBIRD_NCHWXX);
  2354. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2355. *conv_bias_bias = nullptr;
  2356. auto new_filter =
  2357. RelayoutPlaceholder::make(new_inp[1], is_trans.second);
  2358. conv_bias_filter = new_filter.node();
  2359. //! bias trans to nchwxx mode, bias may be scale
  2360. if (new_inp.size() > 2) {
  2361. if (new_inp[2]->shape().ndim == 4) {
  2362. auto new_bias = RelayoutPlaceholder::make(
  2363. new_inp[2], src_to_nchwxx_mode);
  2364. conv_bias_bias = new_bias.node();
  2365. } else {
  2366. mgb_assert(new_inp[2]->shape().ndim == 5);
  2367. conv_bias_bias = new_inp[2];
  2368. }
  2369. }
  2370. mgb_assert(conv_bias_src->shape().ndim == 4 &&
  2371. conv_bias_filter->shape().ndim == 5);
  2372. auto new_param = conv_bias_opr.param();
  2373. new_param.format = conv_bias_format;
  2374. SymbolVar new_conv_bias_opr;
  2375. if (conv_bias_bias) {
  2376. new_conv_bias_opr = opr::ConvBias::make(
  2377. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2378. new_param, conv_bias_opr.execution_policy(),
  2379. conv_bias_opr.config());
  2380. } else {
  2381. new_conv_bias_opr = opr::ConvBias::make(
  2382. conv_bias_src, conv_bias_filter, new_param,
  2383. conv_bias_opr.execution_policy(),
  2384. conv_bias_opr.config());
  2385. }
  2386. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2387. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2388. "The conv dst dim is not trans to nchwxx");
  2389. return new_opr;
  2390. }
  2391. };
  2392. auto replace_pooling_opr = [=](OperatorNodeBase* opr,
  2393. const VarNodeArray& new_inp) {
  2394. mgb_assert(opr->input().size() == new_inp.size());
  2395. auto& pooling_opr = opr->cast_final_safe<opr::PoolingForward>();
  2396. mgb_throw_if(
  2397. pooling_opr.param().format !=
  2398. megdnn::param::Pooling::Format::NCHW,
  2399. MegBrainError,
  2400. "ConvertFormat Pass only support converting NCHW to NCHWxx");
  2401. VarNode* inp = new_inp[0];
  2402. //! if input is nchwxx
  2403. if (inp->shape().ndim == 5) {
  2404. auto new_param = pooling_opr.param();
  2405. new_param.format = pooling_format;
  2406. auto new_pooling_opr =
  2407. opr::PoolingForward::make(inp, new_param, opr->config());
  2408. mgb_assert(new_pooling_opr.shape().ndim == 5,
  2409. "The pooling dst dim is not trans to nchwxx");
  2410. return new_pooling_opr.node()->owner_opr();
  2411. } else {
  2412. auto new_opr = serialization::copy_opr_shallow(*opr, new_inp,
  2413. opr->config());
  2414. return new_opr;
  2415. }
  2416. };
  2417. //! When input change and all input can convert to nchwxx, this opr will run
  2418. //! in nchwxx mode, else it will run in nchw mode, for example concat and
  2419. //! elemwise opr
  2420. auto replace_multi_inp_opr = [=](OperatorNodeBase* opr,
  2421. const VarNodeArray& new_inp) {
  2422. mgb_assert(opr->input().size() == new_inp.size());
  2423. bool has_inp_changed = false;
  2424. bool can_exec_ncwxx = true;
  2425. for (size_t i = 0; i < opr->input().size(); i++) {
  2426. if (new_inp[i]->shape().ndim == 5) {
  2427. has_inp_changed = true;
  2428. } else if (new_inp[i]->shape().ndim == 4) {
  2429. if (new_inp[i]->shape()[1] % pack_c_size != 0) {
  2430. can_exec_ncwxx = false;
  2431. }
  2432. } else if (!new_inp[i]->shape().is_scalar()) {
  2433. can_exec_ncwxx = false;
  2434. }
  2435. }
  2436. if (has_inp_changed) {
  2437. auto temp_inp = new_inp;
  2438. if (can_exec_ncwxx) {
  2439. for (size_t i = 0; i < opr->input().size(); i++) {
  2440. if (new_inp[i]->shape().ndim == 4) {
  2441. auto new_var = RelayoutPlaceholder::make(
  2442. new_inp[i], src_to_nchwxx_mode);
  2443. temp_inp[i] = new_var.node();
  2444. } else {
  2445. mgb_assert((new_inp[i]->shape().ndim == 5) ||
  2446. new_inp[i]->shape().is_scalar());
  2447. }
  2448. }
  2449. } else {
  2450. for (size_t i = 0; i < opr->input().size(); i++) {
  2451. if (new_inp[i]->shape().ndim == 5) {
  2452. auto new_var = RelayoutPlaceholder::make(
  2453. new_inp[i], src_to_nchw_mode);
  2454. temp_inp[i] = new_var.node();
  2455. }
  2456. }
  2457. }
  2458. return serialization::copy_opr_shallow(*opr, temp_inp,
  2459. opr->config());
  2460. } else {
  2461. return serialization::copy_opr_shallow(*opr, new_inp,
  2462. opr->config());
  2463. }
  2464. };
  2465. auto relayout_inp_to_nchw = [=](OperatorNodeBase* opr,
  2466. const VarNodeArray& new_inp) {
  2467. mgb_assert(opr->input().size() == new_inp.size());
  2468. VarNodeArray temp_inp = new_inp;
  2469. for (size_t i = 0; i < opr->input().size(); i++) {
  2470. if (!opr->input(i)->shape().eq_shape(new_inp[i]->shape())) {
  2471. mgb_assert(opr->input(i)->shape().ndim == 4);
  2472. mgb_assert(new_inp[i]->shape().ndim == 5);
  2473. auto new_var =
  2474. RelayoutPlaceholder::make(new_inp[i], src_to_nchw_mode);
  2475. temp_inp[i] = new_var.node();
  2476. }
  2477. }
  2478. return serialization::copy_opr_shallow(*opr, temp_inp, opr->config());
  2479. };
  2480. auto&& replace_func = m_opr_replace_func;
  2481. //! supportted nchwxx
  2482. replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
  2483. replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
  2484. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  2485. replace_func[opr::Concat::typeinfo()] = replace_multi_inp_opr;
  2486. replace_func[opr::Elemwise::typeinfo()] = replace_multi_inp_opr;
  2487. replace_func[opr::TypeCvt::typeinfo()] = replace_multi_inp_opr;
  2488. replace_func[opr::ElemwiseMultiType::typeinfo()] = replace_multi_inp_opr;
  2489. replace_func[opr::PowC::typeinfo()] = replace_multi_inp_opr;
  2490. //! not support yet
  2491. replace_func[opr::ConvolutionBackwardData::typeinfo()] =
  2492. relayout_inp_to_nchw;
  2493. replace_func[opr::Subtensor::typeinfo()] = relayout_inp_to_nchw;
  2494. replace_func[opr::GetVarShape::typeinfo()] = relayout_inp_to_nchw;
  2495. replace_func[opr::Dimshuffle::typeinfo()] = relayout_inp_to_nchw;
  2496. replace_func[opr::Reduce::typeinfo()] = relayout_inp_to_nchw;
  2497. replace_func[opr::AssertEqual::typeinfo()] = relayout_inp_to_nchw;
  2498. replace_func[opr::IncrSubtensor::typeinfo()] = relayout_inp_to_nchw;
  2499. replace_func[opr::ResizeForward::typeinfo()] = relayout_inp_to_nchw;
  2500. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  2501. relayout_inp_to_nchw;
  2502. replace_func[opr::WarpAffineForward::typeinfo()] = relayout_inp_to_nchw;
  2503. replace_func[opr::Reshape::typeinfo()] = relayout_inp_to_nchw;
  2504. replace_func[opr::AxisAddRemove::typeinfo()] = relayout_inp_to_nchw;
  2505. replace_func[opr::Argmax::typeinfo()] = relayout_inp_to_nchw;
  2506. replace_func[opr::Broadcast::typeinfo()] = relayout_inp_to_nchw;
  2507. replace_func[opr::ImmutableTensor::typeinfo()] = relayout_inp_to_nchw;
  2508. }
  2509. std::unique_ptr<EnableNchwxxPass> EnableNchwxxPass::make_nchwxx_converter(
  2510. size_t pack_c_size) {
  2511. MIDOUT_B("EnableNchwxxPass::make")
  2512. auto ret = std::make_unique<EnableNchwxxPass>(pack_c_size);
  2513. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  2514. std::string convter_pass_name = "conv_format_nchw88";
  2515. if (pack_c_size == 4) {
  2516. convter_pass_name = "conv_format_nchw44";
  2517. }
  2518. ret->fill_opr_convert_fun(pack_c_size);
  2519. ret->set_name(convter_pass_name);
  2520. return ret;
  2521. MIDOUT_E
  2522. }
  2523. /* ================ EnableNchw44DotPass =============== */
  2524. VarNode* EnableNchw44DotPass::on_graph_endpoint_var(VarNode* new_var,
  2525. VarNode* orig_var) const {
  2526. if (!orig_var->shape().eq_shape(new_var->shape())) {
  2527. return RelayoutPlaceholder::make(
  2528. new_var, RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW)
  2529. .node();
  2530. }
  2531. return new_var;
  2532. }
  2533. std::unique_ptr<EnableNchw44DotPass>
  2534. EnableNchw44DotPass::make_nchw44_dot_converter() {
  2535. MIDOUT_B("EnableNchw44DotPass::make")
  2536. auto ret = std::make_unique<EnableNchw44DotPass>();
  2537. ret->set_var_replace_check_flag(VarReplaceCheckFlag::NOCHECK);
  2538. //! First is whether the conv can trans to nchwxx, second is the filter
  2539. //! trans mode
  2540. using RelayoutMode = RelayoutPlaceholder::LayoutType;
  2541. struct TestTransResult {
  2542. TransType trans_type;
  2543. RelayoutMode relayout_mod;
  2544. megdnn::param::Convolution::Format conv_format;
  2545. };
  2546. constexpr size_t pack_c_size = 4_z;
  2547. auto test_trans_nchw44_dot =
  2548. [](const megdnn::param::Convolution::Sparse conv_mode,
  2549. const VarNode* filter, const size_t stride_h,
  2550. const size_t stride_w,
  2551. const bool valid_nchw_nchw44) -> TestTransResult {
  2552. TestTransResult ret{TransType::TRANS_NONE, {}, {}};
  2553. bool is_int8 = filter->dtype().enumv() == DTypeEnum::QuantizedS8 ||
  2554. filter->dtype().enumv() == DTypeEnum::Int8;
  2555. if (conv_mode == megdnn::param::Convolution::Sparse::DENSE) {
  2556. size_t OC = filter->shape()[0];
  2557. size_t IC = filter->shape()[1];
  2558. if ((IC % pack_c_size == 0) && (OC % pack_c_size == 0)) {
  2559. ret.trans_type = TransType::TRANS_PURE_NCHWXX;
  2560. if (is_int8) {
  2561. ret.relayout_mod =
  2562. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DOT_DENSE;
  2563. ret.conv_format =
  2564. megdnn::param::ConvBias::Format::NCHW44_DOT;
  2565. } else {
  2566. ret.relayout_mod =
  2567. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DENSE;
  2568. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2569. }
  2570. } else if (valid_nchw_nchw44) {
  2571. ret.trans_type = TransType::TRANS_HYBIRD_NCHWXX;
  2572. ret.relayout_mod = RelayoutMode::WEIGHT_HYBIRD_NCHW_NCHW44;
  2573. if (is_int8) {
  2574. ret.conv_format =
  2575. megdnn::param::ConvBias::Format::NCHW44_DOT;
  2576. } else {
  2577. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2578. }
  2579. }
  2580. } else {
  2581. mgb_throw_if(conv_mode != megdnn::param::Convolution::Sparse::GROUP,
  2582. MegBrainError, "mode error");
  2583. size_t group = filter->shape()[0];
  2584. size_t ocpg = filter->shape()[1];
  2585. size_t icpg = filter->shape()[2];
  2586. if (icpg == 1 && ocpg == 1 && (group % pack_c_size == 0)) {
  2587. ret.trans_type = TransType::TRANS_PURE_NCHWXX;
  2588. ret.relayout_mod = RelayoutMode::WEIGHT_NCHW_TO_NCHW44_CHAN;
  2589. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2590. } else if ((icpg % pack_c_size == 0) && (ocpg % pack_c_size == 0)) {
  2591. ret.trans_type = TransType::TRANS_PURE_NCHWXX;
  2592. if (is_int8) {
  2593. ret.relayout_mod =
  2594. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_DOT_GROUP;
  2595. ret.conv_format =
  2596. megdnn::param::ConvBias::Format::NCHW44_DOT;
  2597. } else {
  2598. ret.relayout_mod =
  2599. RelayoutMode::WEIGHT_NCHW_TO_NCHW44_GROUP;
  2600. ret.conv_format = megdnn::param::ConvBias::Format::NCHW44;
  2601. }
  2602. }
  2603. }
  2604. return ret;
  2605. };
  2606. auto replace_conv_opr = [test_trans_nchw44_dot](
  2607. OperatorNodeBase* opr,
  2608. const VarNodeArray& new_inp) {
  2609. mgb_assert(opr->input().size() == new_inp.size());
  2610. auto& conv_opr = opr->cast_final_safe<opr::ConvolutionForward>();
  2611. mgb_throw_if(conv_opr.param().format !=
  2612. megdnn::param::Convolution::Format::NCHW,
  2613. MegBrainError,
  2614. "ConvertFormat Pass only support converting NCHW to "
  2615. "NCHW44_DOT");
  2616. bool valid_nchw_nchw44 = nchw_nchwxx_valid(
  2617. conv_opr, new_inp, pack_c_size,
  2618. megdnn::param::ConvBias::NonlineMode::IDENTITY, true);
  2619. auto is_trans = test_trans_nchw44_dot(
  2620. conv_opr.param().sparse, new_inp[1], conv_opr.param().stride_h,
  2621. conv_opr.param().stride_w, valid_nchw_nchw44);
  2622. //! can not trans to nchwxx
  2623. if (is_trans.trans_type == TransType::TRANS_NONE) {
  2624. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2625. new_inp[1]->shape().ndim == 5,
  2626. "The origin filter is not NCHW mode");
  2627. VarNodeArray temp_inp = new_inp;
  2628. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  2629. if (temp_inp[0]->shape().ndim == 5) {
  2630. auto new_src = RelayoutPlaceholder::make(
  2631. new_inp[0], RelayoutMode::NCHW4_TO_NCHW);
  2632. temp_inp[0] = new_src.node();
  2633. }
  2634. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  2635. opr->config());
  2636. return new_opr;
  2637. } else if (is_trans.trans_type == TransType::TRANS_PURE_NCHWXX) {
  2638. //! filter trans to nchwxx mode
  2639. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2640. new_inp[1]->shape().ndim == 5,
  2641. "The origin filter is not NCHW mode");
  2642. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  2643. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2644. is_trans.relayout_mod);
  2645. conv_filter = new_filter.node();
  2646. //! src trans to nchwxx mode
  2647. if (new_inp[0]->shape().ndim != 5) {
  2648. mgb_assert(new_inp[0]->shape().ndim == 4);
  2649. auto new_src = RelayoutPlaceholder::make(
  2650. new_inp[0], RelayoutMode::NCHW_TO_NCHW4);
  2651. conv_src = new_src.node();
  2652. }
  2653. auto new_param = conv_opr.param();
  2654. new_param.format = is_trans.conv_format;
  2655. mgb_assert(conv_src->shape().ndim == 5 &&
  2656. conv_filter->shape().ndim >= 6,
  2657. "The conv src dim is not trans to nchwxx");
  2658. auto new_conv_opr = opr::Convolution::make(
  2659. conv_src, conv_filter, new_param,
  2660. conv_opr.execution_policy(), conv_opr.config());
  2661. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  2662. mgb_assert(new_conv_opr.shape().ndim == 5,
  2663. "The conv dst dim is not trans to nchwxx");
  2664. return new_opr;
  2665. } else {
  2666. mgb_assert(is_trans.trans_type == TransType::TRANS_HYBIRD_NCHWXX);
  2667. VarNode *conv_src = new_inp[0], *conv_filter = new_inp[1];
  2668. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2669. is_trans.relayout_mod);
  2670. conv_filter = new_filter.node();
  2671. mgb_assert(conv_src->shape().ndim == 4 &&
  2672. conv_filter->shape().ndim == 5,
  2673. "The src and filter is OK");
  2674. auto new_param = conv_opr.param();
  2675. new_param.format = is_trans.conv_format;
  2676. auto new_conv_opr = opr::Convolution::make(
  2677. conv_src, conv_filter, new_param,
  2678. conv_opr.execution_policy(), conv_opr.config());
  2679. OperatorNodeBase* new_opr = new_conv_opr.node()->owner_opr();
  2680. mgb_assert(new_conv_opr.shape().ndim == 5,
  2681. "The conv dst dim is not trans to nchwxx");
  2682. return new_opr;
  2683. }
  2684. };
  2685. auto replace_conv_bias_opr = [test_trans_nchw44_dot](
  2686. OperatorNodeBase* opr,
  2687. const VarNodeArray& new_inp) {
  2688. mgb_assert(opr->input().size() == new_inp.size());
  2689. mgb_assert(opr->input().size() <= 3,
  2690. "nchwxx-dot does not support conv_bias fuse Z right now");
  2691. auto& conv_bias_opr = opr->cast_final_safe<opr::ConvBiasForward>();
  2692. mgb_throw_if(
  2693. conv_bias_opr.param().format !=
  2694. megdnn::param::ConvBias::Format::NCHW,
  2695. MegBrainError,
  2696. "ConvertFormat Pass only support converting NCHW to NCHWXX");
  2697. bool valid_nchw_nchw44 =
  2698. nchw_nchwxx_valid(conv_bias_opr, new_inp, pack_c_size,
  2699. conv_bias_opr.param().nonlineMode, true);
  2700. auto is_trans = test_trans_nchw44_dot(
  2701. conv_bias_opr.param().sparse, new_inp[1],
  2702. conv_bias_opr.param().stride_h, conv_bias_opr.param().stride_w,
  2703. valid_nchw_nchw44);
  2704. auto megdnn_conv =
  2705. opr::intl::get_megdnn_handle(conv_bias_opr.comp_node())
  2706. ->create_operator<megdnn::ConvBiasForward>();
  2707. SmallVector<TensorLayout> layouts;
  2708. //! can not trans to nchwxx
  2709. if (is_trans.trans_type == TransType::TRANS_NONE) {
  2710. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2711. new_inp[1]->shape().ndim == 5,
  2712. "The origin filter is not NCHW mode");
  2713. VarNodeArray temp_inp = new_inp;
  2714. //! if src is nchwxx, should RelayoutPlaceholder to nchw
  2715. if (temp_inp[0]->shape().ndim == 5) {
  2716. auto new_src = RelayoutPlaceholder::make(
  2717. new_inp[0], RelayoutMode::NCHW4_TO_NCHW);
  2718. temp_inp[0] = new_src.node();
  2719. }
  2720. //! the bias is nchwxx
  2721. if (new_inp.size() > 2 && temp_inp[2]->shape().ndim == 5) {
  2722. auto new_bias = RelayoutPlaceholder::make(
  2723. new_inp[2], RelayoutMode::NCHW4_TO_NCHW);
  2724. temp_inp[2] = new_bias.node();
  2725. }
  2726. auto new_opr = serialization::copy_opr_shallow(*opr, temp_inp,
  2727. opr->config());
  2728. return new_opr;
  2729. } else if (is_trans.trans_type == TransType::TRANS_PURE_NCHWXX) {
  2730. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2731. *conv_bias_bias = nullptr;
  2732. //! filter trans to nchwxx mode
  2733. mgb_assert(new_inp[1]->shape().ndim == 4 ||
  2734. new_inp[1]->shape().ndim == 5,
  2735. "The origin filter is not NCHW mode");
  2736. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2737. is_trans.relayout_mod);
  2738. conv_bias_filter = new_filter.node();
  2739. //! src trans to nchwxx mode
  2740. if (new_inp[0]->shape().ndim != 5) {
  2741. mgb_assert(new_inp[0]->shape().ndim == 4);
  2742. auto new_src = RelayoutPlaceholder::make(
  2743. new_inp[0], RelayoutMode::NCHW_TO_NCHW4);
  2744. conv_bias_src = new_src.node();
  2745. }
  2746. //! bias trans to nchwxx mode
  2747. if (new_inp.size() > 2) {
  2748. if (new_inp[2]->shape().ndim == 4) {
  2749. auto new_bias = RelayoutPlaceholder::make(
  2750. new_inp[2], RelayoutMode::NCHW_TO_NCHW4);
  2751. conv_bias_bias = new_bias.node();
  2752. } else {
  2753. mgb_assert(new_inp[2]->shape().ndim == 5);
  2754. conv_bias_bias = new_inp[2];
  2755. }
  2756. }
  2757. auto new_param = conv_bias_opr.param();
  2758. new_param.format = is_trans.conv_format;
  2759. mgb_assert(conv_bias_src->shape().ndim == 5 &&
  2760. conv_bias_filter->shape().ndim >= 6,
  2761. "The conv_bias src dim is not trans to nchwxx");
  2762. SymbolVar new_conv_bias_opr;
  2763. if (conv_bias_bias) {
  2764. new_conv_bias_opr = opr::ConvBias::make(
  2765. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2766. new_param, conv_bias_opr.execution_policy(),
  2767. conv_bias_opr.config());
  2768. } else {
  2769. new_conv_bias_opr = opr::ConvBias::make(
  2770. conv_bias_src, conv_bias_filter, new_param,
  2771. conv_bias_opr.execution_policy(),
  2772. conv_bias_opr.config());
  2773. }
  2774. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2775. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2776. "The conv_bias dst dim is not trans to nchwxx");
  2777. return new_opr;
  2778. } else {
  2779. mgb_assert(is_trans.trans_type == TransType::TRANS_HYBIRD_NCHWXX);
  2780. VarNode *conv_bias_src = new_inp[0], *conv_bias_filter = new_inp[1],
  2781. *conv_bias_bias = nullptr;
  2782. auto new_filter = RelayoutPlaceholder::make(new_inp[1],
  2783. is_trans.relayout_mod);
  2784. conv_bias_filter = new_filter.node();
  2785. //! bias trans to nchwxx mode, bias may be scale
  2786. if (new_inp.size() > 2) {
  2787. if (new_inp[2]->shape().ndim == 4) {
  2788. auto new_bias = RelayoutPlaceholder::make(
  2789. new_inp[2], RelayoutMode::NCHW_TO_NCHW4);
  2790. conv_bias_bias = new_bias.node();
  2791. } else {
  2792. mgb_assert(new_inp[2]->shape().ndim == 5);
  2793. conv_bias_bias = new_inp[2];
  2794. }
  2795. }
  2796. mgb_assert(conv_bias_src->shape().ndim == 4 &&
  2797. conv_bias_filter->shape().ndim == 5);
  2798. auto new_param = conv_bias_opr.param();
  2799. new_param.format = is_trans.conv_format;
  2800. SymbolVar new_conv_bias_opr;
  2801. if (conv_bias_bias) {
  2802. new_conv_bias_opr = opr::ConvBias::make(
  2803. conv_bias_src, conv_bias_filter, conv_bias_bias,
  2804. new_param, conv_bias_opr.execution_policy(),
  2805. conv_bias_opr.config());
  2806. } else {
  2807. new_conv_bias_opr = opr::ConvBias::make(
  2808. conv_bias_src, conv_bias_filter, new_param,
  2809. conv_bias_opr.execution_policy(),
  2810. conv_bias_opr.config());
  2811. }
  2812. OperatorNodeBase* new_opr = new_conv_bias_opr.node()->owner_opr();
  2813. mgb_assert(new_conv_bias_opr.shape().ndim == 5,
  2814. "The conv dst dim is not trans to nchwxx");
  2815. return new_opr;
  2816. }
  2817. };
  2818. ret->fill_opr_convert_fun(4);
  2819. auto&& replace_func = ret->m_opr_replace_func;
  2820. //! supportted nchwxx
  2821. replace_func[opr::Convolution::typeinfo()] = replace_conv_opr;
  2822. replace_func[opr::ConvBias::typeinfo()] = replace_conv_bias_opr;
  2823. return ret;
  2824. MIDOUT_E
  2825. }
  2826. /* ==================== ShuffleShuffleRemovePass ================= */
  2827. class ShuffleShuffleRemovePass::Impl {
  2828. using TensorFormat = opr::ConvBias::Param::Format;
  2829. OptState& m_opt_state;
  2830. ThinHashMap<std::pair<TensorFormat, TensorFormat>,
  2831. thin_function<VarNode*(VarNode*)>>
  2832. m_reformat;
  2833. class AbstractShuffleOpr;
  2834. void detect_shuffle_operations();
  2835. void do_replace();
  2836. public:
  2837. Impl(OptState& opt_state) : m_opt_state{opt_state} {
  2838. m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::NCHW4)] =
  2839. [](VarNode* inp) -> VarNode* {
  2840. auto x = SymbolVar(inp);
  2841. auto xshp = opr::GetVarShape::make(x);
  2842. auto cv = [&x](int v) { return x.make_scalar(v); };
  2843. auto sub = [&xshp, &cv](int idx) {
  2844. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2845. };
  2846. auto tshp = opr::Concat::make(
  2847. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
  2848. auto y0 = opr::Reshape::make(x, tshp);
  2849. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  2850. return y1.node();
  2851. };
  2852. m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::NCHW32)] =
  2853. [](VarNode* inp) -> VarNode* {
  2854. auto x = SymbolVar(inp);
  2855. auto xshp = opr::GetVarShape::make(x);
  2856. auto cv = [&x](int v) { return x.make_scalar(v); };
  2857. auto sub = [&xshp, &cv](int idx) {
  2858. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2859. };
  2860. auto tshp = opr::Concat::make(
  2861. {sub(0), sub(1) / 32, cv(32), sub(2), sub(3)}, 0);
  2862. auto y0 = opr::Reshape::make(x, tshp);
  2863. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2});
  2864. return y1.node();
  2865. };
  2866. m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::NCHW)] =
  2867. [](VarNode* inp) -> VarNode* {
  2868. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  2869. auto x = SymbolVar(inp);
  2870. auto xshp = opr::GetVarShape::make(x);
  2871. auto cv = [&x](int v) { return x.make_scalar(v); };
  2872. auto sub = [&xshp, &cv](int idx) {
  2873. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2874. };
  2875. auto tshp =
  2876. opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
  2877. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  2878. auto y1 = opr::Reshape::make(y0, tshp);
  2879. return y1.node();
  2880. };
  2881. m_reformat[std::make_pair(TensorFormat::NCHW32, TensorFormat::NCHW)] =
  2882. [](VarNode* inp) -> VarNode* {
  2883. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
  2884. auto x = SymbolVar(inp);
  2885. auto xshp = opr::GetVarShape::make(x);
  2886. auto cv = [&x](int v) { return x.make_scalar(v); };
  2887. auto sub = [&xshp, &cv](int idx) {
  2888. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2889. };
  2890. auto tshp =
  2891. opr::Concat::make({sub(0), sub(1) * 32, sub(2), sub(3)}, 0);
  2892. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  2893. auto y1 = opr::Reshape::make(y0, tshp);
  2894. return y1.node();
  2895. };
  2896. m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::NCHW32)] =
  2897. [](VarNode* inp) -> VarNode* {
  2898. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  2899. auto x = SymbolVar(inp);
  2900. auto xshp = opr::GetVarShape::make(x);
  2901. auto cv = [&x](int v) { return x.make_scalar(v); };
  2902. auto sub = [&xshp, &cv](int idx) {
  2903. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2904. };
  2905. auto tshp0 = opr::Concat::make(
  2906. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)},
  2907. 0),
  2908. tshp1 = opr::Concat::make(
  2909. {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
  2910. auto y0 = opr::Reshape::make(x, tshp0);
  2911. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  2912. auto y2 = opr::Reshape::make(y1, tshp1);
  2913. return y2.node();
  2914. };
  2915. m_reformat[std::make_pair(TensorFormat::NCHW32, TensorFormat::NCHW4)] =
  2916. [](VarNode* inp) -> VarNode* {
  2917. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
  2918. auto x = SymbolVar(inp);
  2919. auto xshp = opr::GetVarShape::make(x);
  2920. auto cv = [&x](int v) { return x.make_scalar(v); };
  2921. auto sub = [&xshp, &cv](int idx) {
  2922. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2923. };
  2924. auto tshp0 = opr::Concat::make(
  2925. {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8},
  2926. 0),
  2927. tshp1 = opr::Concat::make(
  2928. {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
  2929. auto y0 = opr::Reshape::make(x, tshp0);
  2930. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  2931. auto y2 = opr::Reshape::make(y1, tshp1);
  2932. return y2.node();
  2933. };
  2934. m_reformat[std::make_pair(TensorFormat::NCHW4, TensorFormat::CHWN4)] =
  2935. [](VarNode* inp) -> VarNode* {
  2936. megdnn::param::RelayoutFormat param;
  2937. param.mode = megdnn::param::RelayoutFormat::Mode::NCHW4_CHWN4;
  2938. auto reformat = opr::RelayoutFormat::make(inp, param);
  2939. return reformat.node();
  2940. };
  2941. m_reformat[std::make_pair(TensorFormat::CHWN4, TensorFormat::NCHW4)] =
  2942. [](VarNode* inp) -> VarNode* {
  2943. megdnn::param::RelayoutFormat param;
  2944. param.mode = megdnn::param::RelayoutFormat::Mode::CHWN4_NCHW4;
  2945. auto reformat = opr::RelayoutFormat::make(inp, param);
  2946. return reformat.node();
  2947. };
  2948. m_reformat[std::make_pair(TensorFormat::NCHW, TensorFormat::CHWN4)] =
  2949. [](VarNode* inp) -> VarNode* {
  2950. auto x = SymbolVar(inp);
  2951. auto xshp = opr::GetVarShape::make(x);
  2952. auto cv = [&x](int v) { return x.make_scalar(v); };
  2953. auto sub = [&xshp, &cv](int idx) {
  2954. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2955. };
  2956. auto tshp = opr::Concat::make(
  2957. {sub(0), sub(1) / 4, cv(4), sub(2), sub(3)}, 0);
  2958. auto y0 = opr::Reshape::make(x, tshp);
  2959. auto y1 = opr::Dimshuffle::make(y0, {1, 3, 4, 0, 2});
  2960. return y1.node();
  2961. };
  2962. m_reformat[std::make_pair(TensorFormat::CHWN4, TensorFormat::NCHW)] =
  2963. [](VarNode* inp) -> VarNode* {
  2964. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  2965. auto x = SymbolVar(inp);
  2966. auto xshp = opr::GetVarShape::make(x);
  2967. auto cv = [&x](int v) { return x.make_scalar(v); };
  2968. auto sub = [&xshp, &cv](int idx) {
  2969. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  2970. };
  2971. auto tshp =
  2972. opr::Concat::make({sub(3), sub(0) * 4, sub(1), sub(2)}, 0);
  2973. auto y0 = opr::Dimshuffle::make(x, {3, 0, 4, 1, 2});
  2974. auto y1 = opr::Reshape::make(y0, tshp);
  2975. return y1.node();
  2976. };
  2977. detect_shuffle_operations();
  2978. do_replace();
  2979. }
  2980. };
  2981. /*!
  2982. * \brief abstract operator representation of shuffle operation
  2983. */
  2984. MGB_DEFINE_OPR_CLASS(ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr,
  2985. cg::SingleCNOperatorNodeBase) // {
  2986. public:
  2987. AbstractShuffleOpr(VarNode* inpvar, TensorFormat inp_format,
  2988. TensorFormat out_format);
  2989. static SymbolVar make(VarNode* inpvar, TensorFormat inp_format,
  2990. TensorFormat out_format);
  2991. TensorFormat inp_format() const {
  2992. return m_inp_format;
  2993. }
  2994. TensorFormat out_format() const {
  2995. return m_out_format;
  2996. }
  2997. private:
  2998. void init_output_static_infer_desc() override;
  2999. void scn_do_execute() override;
  3000. const TensorFormat m_inp_format;
  3001. const TensorFormat m_out_format;
  3002. };
  3003. MGB_DYN_TYPE_OBJ_FINAL_IMPL(ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr);
  3004. void ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::scn_do_execute() {
  3005. mgb_throw(InternalError, "AbstractShuffleOpr cannot be executed");
  3006. }
  3007. void ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::
  3008. init_output_static_infer_desc() {
  3009. using namespace cg::static_infer;
  3010. auto&& mgr = owner_graph()->static_infer_manager();
  3011. DepVal deps;
  3012. for (auto i : input())
  3013. deps.push_back({i, DepType::SHAPE});
  3014. auto infer_shape = [this](TensorShape& dst, const InpVal& inp) {
  3015. TensorShape inp_shape = inp.val[0].shape();
  3016. if (m_inp_format == TensorFormat::NCHW4 &&
  3017. m_out_format == TensorFormat::NCHW32) {
  3018. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  3019. dst = inp_shape;
  3020. dst[0] = inp_shape[0];
  3021. dst[1] = inp_shape[1] / 8;
  3022. dst[2] = inp_shape[2];
  3023. dst[3] = inp_shape[3];
  3024. dst[4] = inp_shape[4] * 8;
  3025. } else if (m_inp_format == TensorFormat::NCHW32 &&
  3026. m_out_format == TensorFormat::NCHW4) {
  3027. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 32);
  3028. dst = inp_shape;
  3029. dst[0] = inp_shape[0];
  3030. dst[1] = inp_shape[1] * 8;
  3031. dst[2] = inp_shape[2];
  3032. dst[3] = inp_shape[3];
  3033. dst[4] = inp_shape[4] / 8;
  3034. } else if (m_inp_format == TensorFormat::NCHW &&
  3035. m_out_format == TensorFormat::NCHW4) {
  3036. mgb_assert(inp_shape.ndim == 4);
  3037. dst.ndim = 5;
  3038. dst[0] = inp_shape[0];
  3039. dst[1] = inp_shape[1] / 4;
  3040. dst[2] = inp_shape[2];
  3041. dst[3] = inp_shape[3];
  3042. dst[4] = 4;
  3043. } else if (m_inp_format == TensorFormat::NCHW4 &&
  3044. m_out_format == TensorFormat::NCHW) {
  3045. mgb_assert(inp_shape.ndim == 5 && inp_shape[4] == 4);
  3046. dst.ndim = 4;
  3047. dst[0] = inp_shape[0];
  3048. dst[1] = inp_shape[1] * 4;
  3049. dst[2] = inp_shape[2];
  3050. dst[3] = inp_shape[3];
  3051. } else if (m_inp_format == TensorFormat::NCHW4 &&
  3052. m_out_format == TensorFormat::CHWN4) {
  3053. dst.ndim = 5;
  3054. dst[0] = inp_shape[1];
  3055. dst[1] = inp_shape[2];
  3056. dst[2] = inp_shape[3];
  3057. dst[3] = inp_shape[0];
  3058. dst[4] = inp_shape[4];
  3059. } else if (m_inp_format == TensorFormat::CHWN4 &&
  3060. m_out_format == TensorFormat::NCHW4) {
  3061. dst.ndim = 5;
  3062. dst[0] = inp_shape[3];
  3063. dst[1] = inp_shape[0];
  3064. dst[2] = inp_shape[1];
  3065. dst[3] = inp_shape[2];
  3066. dst[4] = inp_shape[4];
  3067. } else {
  3068. mgb_throw(InternalError,
  3069. "Unsupported input format and output format.");
  3070. }
  3071. return true;
  3072. };
  3073. mgr.register_shape_infer(output(0), {SourceType::DEP, deps, infer_shape});
  3074. }
  3075. ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::AbstractShuffleOpr(
  3076. VarNode* inpvar, TensorFormat inp_format, TensorFormat out_format)
  3077. : Super(inpvar->owner_graph(), {}, "AbstractShuffleOpr", {inpvar}),
  3078. m_inp_format{inp_format},
  3079. m_out_format{out_format} {
  3080. add_input({inpvar});
  3081. add_equivalence_component<ScalarHash<TensorFormat>>(m_inp_format);
  3082. add_equivalence_component<ScalarHash<TensorFormat>>(m_out_format);
  3083. add_output(None)->dtype(inpvar->dtype());
  3084. }
  3085. SymbolVar ShuffleShuffleRemovePass::Impl::AbstractShuffleOpr::make(
  3086. VarNode* inpvar, TensorFormat inp_format, TensorFormat out_format) {
  3087. return inpvar->owner_graph()
  3088. ->insert_opr(std::make_unique<AbstractShuffleOpr>(
  3089. inpvar, inp_format, out_format))
  3090. ->output(0);
  3091. }
  3092. void ShuffleShuffleRemovePass::Impl::detect_shuffle_operations() {
  3093. auto rewriter = m_opt_state.graph().make_rewriter();
  3094. auto uniq_reader_check = UniqReaderCheck{m_opt_state.graph()};
  3095. auto try_reshape_shuffle = [&rewriter,
  3096. &uniq_reader_check](OperatorNodeBase* opr) {
  3097. // check shuffle
  3098. auto shuffle = try_cast_as_op<opr::Dimshuffle>(opr);
  3099. if (shuffle == nullptr)
  3100. return false;
  3101. auto&& param = shuffle->param();
  3102. if (param.pattern_len != 5)
  3103. return false;
  3104. bool is_nchw2nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3105. param.pattern[2] == 3 && param.pattern[3] == 4 &&
  3106. param.pattern[4] == 2 &&
  3107. opr->output(0)->shape()[4] == 4;
  3108. if (!is_nchw2nchw4)
  3109. return false;
  3110. if (!uniq_reader_check(shuffle->input(0)))
  3111. return false;
  3112. // check reshape
  3113. auto reshape = try_cast_as_op<opr::Reshape>(opr->input(0)->owner_opr());
  3114. if (reshape == nullptr)
  3115. return false;
  3116. auto inp_var = rewriter.get_var(reshape->input(0));
  3117. auto abstract_shuffle = AbstractShuffleOpr::make(
  3118. inp_var, TensorFormat::NCHW, TensorFormat::NCHW4);
  3119. rewriter.replace_var(
  3120. opr->output(0), abstract_shuffle.node(),
  3121. mgb_cstr_log("replace reformat(nchw -> nchw4) to "
  3122. "AbstractShuffleOpr(nchw -> nchw4)."));
  3123. return true;
  3124. };
  3125. auto try_reshape_shuffle_reshape = [&rewriter, &uniq_reader_check](
  3126. OperatorNodeBase* opr) {
  3127. // check reshape
  3128. auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
  3129. if (reshape1 == nullptr)
  3130. return false;
  3131. if (!uniq_reader_check(reshape1->input(0)))
  3132. return false;
  3133. // check shuffle
  3134. auto shuffle =
  3135. try_cast_as_op<opr::Dimshuffle>(opr->input(0)->owner_opr());
  3136. if (shuffle == nullptr)
  3137. return false;
  3138. auto&& param = shuffle->param();
  3139. if (param.pattern_len != 6)
  3140. return false;
  3141. bool is_nchw42nchw32 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3142. param.pattern[2] == 3 && param.pattern[3] == 4 &&
  3143. param.pattern[4] == 2 && param.pattern[5] == 5 &&
  3144. shuffle->input(0)->shape()[5] == 4 &&
  3145. shuffle->input(0)->shape()[2] == 8;
  3146. bool is_nchw322nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3147. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  3148. param.pattern[4] == 3 && param.pattern[5] == 5 &&
  3149. shuffle->input(0)->shape()[4] == 8 &&
  3150. shuffle->input(0)->shape()[5] == 4;
  3151. if (!is_nchw42nchw32 && !is_nchw322nchw4)
  3152. return false;
  3153. if (!uniq_reader_check(shuffle->input(0)))
  3154. return false;
  3155. // check reshape
  3156. auto reshape2 =
  3157. try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
  3158. if (reshape2 == nullptr)
  3159. return false;
  3160. auto inp_var = rewriter.get_var(reshape2->input(0));
  3161. TensorFormat inp_format = is_nchw42nchw32 ? TensorFormat::NCHW4
  3162. : TensorFormat::NCHW32,
  3163. out_format = is_nchw42nchw32 ? TensorFormat::NCHW32
  3164. : TensorFormat::NCHW4;
  3165. auto abstract_shuffle =
  3166. AbstractShuffleOpr::make(inp_var, inp_format, out_format);
  3167. std::string reformat_type =
  3168. is_nchw42nchw32 ? "nchw4 -> nchw32" : "nchw32 -> nchw4";
  3169. rewriter.replace_var(opr->output(0), abstract_shuffle.node(),
  3170. mgb_cstr_log(ssprintf("replace reformat(%s) to "
  3171. "AbstractShuffleOpr(%s).",
  3172. reformat_type.c_str(),
  3173. reformat_type.c_str())
  3174. .c_str()));
  3175. return true;
  3176. };
  3177. auto try_shuffle_reshape = [&rewriter,
  3178. &uniq_reader_check](OperatorNodeBase* opr) {
  3179. // check reshape
  3180. auto reshape = try_cast_as_op<opr::Reshape>(opr);
  3181. if (reshape == nullptr)
  3182. return false;
  3183. if (!uniq_reader_check(reshape->input(0)))
  3184. return false;
  3185. // check shuffle
  3186. auto shuffle =
  3187. try_cast_as_op<opr::Dimshuffle>(opr->input(0)->owner_opr());
  3188. if (shuffle == nullptr)
  3189. return false;
  3190. auto&& param = shuffle->param();
  3191. if (param.pattern_len != 5)
  3192. return false;
  3193. bool is_nchw42nchw = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3194. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  3195. param.pattern[4] == 3 &&
  3196. shuffle->input(0)->shape()[4] == 4;
  3197. if (!is_nchw42nchw)
  3198. return false;
  3199. auto inp_var = rewriter.get_var(shuffle->input(0));
  3200. auto abstract_shuffle = AbstractShuffleOpr::make(
  3201. inp_var, TensorFormat::NCHW4, TensorFormat::NCHW);
  3202. rewriter.replace_var(
  3203. opr->output(0), abstract_shuffle.node(),
  3204. mgb_cstr_log("replace reformat(nchw4 -> nchw) to "
  3205. "AbstractShuffleOpr(nchw4 -> nchw)."));
  3206. return true;
  3207. };
  3208. auto try_relayout_format = [&rewriter](OperatorNodeBase* opr) {
  3209. // check relayout format
  3210. auto reformat = try_cast_as_op<opr::RelayoutFormat>(opr);
  3211. if (reformat == nullptr)
  3212. return false;
  3213. auto&& param = reformat->param();
  3214. if (param.mode != opr::RelayoutFormat::Param::Mode::CHWN4_NCHW4 &&
  3215. param.mode != opr::RelayoutFormat::Param::Mode::NCHW4_CHWN4)
  3216. return false;
  3217. auto inp_var = rewriter.get_var(reformat->input(0));
  3218. cg::SymbolVar abstract_shuffle;
  3219. if (param.mode == opr::RelayoutFormat::Param::Mode::NCHW4_CHWN4) {
  3220. abstract_shuffle = AbstractShuffleOpr::make(
  3221. inp_var, TensorFormat::NCHW4, TensorFormat::CHWN4);
  3222. } else {
  3223. abstract_shuffle = AbstractShuffleOpr::make(
  3224. inp_var, TensorFormat::CHWN4, TensorFormat::NCHW4);
  3225. }
  3226. rewriter.replace_var(
  3227. opr->output(0), abstract_shuffle.node(),
  3228. mgb_cstr_log("replace reformat(nchw4 -> nchw) to "
  3229. "AbstractShuffleOpr(nchw4 -> nchw)."));
  3230. return true;
  3231. };
  3232. auto on_opr = [&try_reshape_shuffle, &try_shuffle_reshape,
  3233. &try_reshape_shuffle_reshape, &try_relayout_format,
  3234. &rewriter, &uniq_reader_check](OperatorNodeBase* opr) {
  3235. if (!try_reshape_shuffle_reshape(opr) && !try_reshape_shuffle(opr) &&
  3236. !try_shuffle_reshape(opr) && !try_relayout_format(opr)) {
  3237. auto new_opr = rewriter.auto_replace_outputs(opr);
  3238. uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
  3239. }
  3240. };
  3241. m_opt_state.graph().iter(on_opr);
  3242. rewriter.apply_inplace();
  3243. }
  3244. void ShuffleShuffleRemovePass::Impl::do_replace() {
  3245. auto rewriter = m_opt_state.graph().make_rewriter();
  3246. auto uniq_reader_check = UniqReaderCheck{m_opt_state.graph()};
  3247. ThinHashSet<OperatorNodeBase*> writers;
  3248. ThinHashSet<OperatorNodeBase*> root;
  3249. ThinHashSet<VarNode*> trt_opr_inps;
  3250. SmallVector<OperatorNodeBase*> topo_order;
  3251. auto cb = [&topo_order, &trt_opr_inps](OperatorNodeBase* opr) {
  3252. topo_order.push_back(opr);
  3253. MGB_MARK_USED_VAR(trt_opr_inps);
  3254. #if MGB_ENABLE_TENSOR_RT
  3255. if (opr->same_type<opr::TensorRTOpr>()) {
  3256. for (auto&& inp : opr->input())
  3257. trt_opr_inps.insert(inp);
  3258. }
  3259. #endif
  3260. };
  3261. m_opt_state.graph().iter(cb);
  3262. for (auto&& opr : reverse_adaptor(topo_order)) {
  3263. if (opr->same_type<opr::TypeCvt>() ||
  3264. opr->same_type<AbstractShuffleOpr>()) {
  3265. writers.insert(opr->input(0)->owner_opr());
  3266. if (writers.count(opr) > 0) {
  3267. if (!uniq_reader_check(opr->output(0))) {
  3268. root.insert(opr);
  3269. }
  3270. } else {
  3271. root.insert(opr);
  3272. }
  3273. }
  3274. }
  3275. auto on_opr = [this, &rewriter, &uniq_reader_check, &trt_opr_inps,
  3276. &root](OperatorNodeBase* opr) {
  3277. MGB_MARK_USED_VAR(trt_opr_inps);
  3278. bool cond_opr = opr->same_type<opr::TypeCvt>() ||
  3279. opr->same_type<AbstractShuffleOpr>();
  3280. if (cond_opr) {
  3281. bool cond_endpoint = root.count(opr) > 0;
  3282. if (!cond_endpoint) {
  3283. return;
  3284. }
  3285. auto cur = opr;
  3286. auto var = opr->output(0), inp_var = opr->input(0);
  3287. bool force_folding_typecvt = false;
  3288. bool first_shuffle = false;
  3289. // initialize inp_format and out_format
  3290. TensorFormat out_format = TensorFormat::NCHW,
  3291. inp_format = out_format;
  3292. megdnn::DType inp_dtype = cur->input(0)->dtype(),
  3293. out_dtype = cur->output(0)->dtype();
  3294. SmallVector<megdnn::DType> out_dtype_vec;
  3295. while (cond_opr) {
  3296. if (cur->same_type<AbstractShuffleOpr>()) {
  3297. auto shuffle = try_cast_as_op<AbstractShuffleOpr>(cur);
  3298. inp_format = shuffle->inp_format();
  3299. if (!first_shuffle) {
  3300. out_format = shuffle->out_format();
  3301. first_shuffle = true;
  3302. }
  3303. } else {
  3304. mgb_assert(cur->same_type<opr::TypeCvt>());
  3305. out_dtype_vec.push_back(cur->output(0)->dtype());
  3306. }
  3307. inp_var = cur->input(0);
  3308. bool cond_reader = uniq_reader_check(inp_var);
  3309. if (!cond_reader)
  3310. break;
  3311. cur = cur->input(0)->owner_opr();
  3312. cond_opr = cur->same_type<opr::TypeCvt>() ||
  3313. cur->same_type<AbstractShuffleOpr>();
  3314. }
  3315. std::reverse(out_dtype_vec.begin(), out_dtype_vec.end());
  3316. #if MGB_ENABLE_TENSOR_RT
  3317. force_folding_typecvt =
  3318. inp_var->owner_opr()->same_type<opr::TensorRTOpr>() ||
  3319. trt_opr_inps.count(var);
  3320. #endif
  3321. auto new_var = rewriter.get_var(inp_var);
  3322. if (inp_format != out_format) {
  3323. mgb_assert(m_reformat.find(std::make_pair(
  3324. inp_format, out_format)) != m_reformat.end(),
  3325. "Unsupported shuffle shuffle remove pass");
  3326. new_var = m_reformat[std::make_pair(inp_format, out_format)](
  3327. new_var);
  3328. }
  3329. if (force_folding_typecvt) {
  3330. inp_dtype = inp_var->dtype();
  3331. if (inp_dtype != out_dtype) {
  3332. auto type_cvt = opr::TypeCvt::make(new_var, out_dtype);
  3333. new_var = type_cvt.node();
  3334. }
  3335. } else {
  3336. if (out_dtype_vec.back() != var->dtype())
  3337. out_dtype_vec.push_back(var->dtype());
  3338. for (auto&& dtype : out_dtype_vec) {
  3339. auto type_cvt = opr::TypeCvt::make(new_var, dtype);
  3340. new_var = type_cvt.node();
  3341. }
  3342. }
  3343. rewriter.replace_var(
  3344. var, new_var,
  3345. mgb_cstr_log("replace Dimshuffle and TypeCvt chain"));
  3346. } else {
  3347. auto new_opr = rewriter.auto_replace_outputs(opr);
  3348. uniq_reader_check.update_on_opr_auto_replace(opr, new_opr);
  3349. }
  3350. };
  3351. m_opt_state.graph().iter(on_opr);
  3352. rewriter.apply_inplace();
  3353. }
  3354. const char* ShuffleShuffleRemovePass::name() const {
  3355. return mgb_cstr_log("shuffle shuffle remove pass");
  3356. }
  3357. void ShuffleShuffleRemovePass::apply(OptState& opt) const {
  3358. MIDOUT_B("ShuffleShuffleRemovePass::apply")
  3359. opt.set_var_replace_check_flag(VarReplaceCheckFlag::CHECK_SHAPE |
  3360. VarReplaceCheckFlag::CHECK_DTYPE);
  3361. Impl{opt};
  3362. MIDOUT_E
  3363. }
  3364. /* ==================== FoldingConvBiasDimshufflePass ================= */
  3365. const char* FoldingConvBiasDimshufflePass::name() const {
  3366. return mgb_cstr_log("folding conv bias dimshuffle pass");
  3367. }
  3368. void FoldingConvBiasDimshufflePass::apply(OptState& opt) const {
  3369. MIDOUT_B("FoldingConvBiasDimshufflePass::apply");
  3370. using DepType = cg::OperatorNodeProp::DepType;
  3371. ThinHashMap<OperatorNodeBase*,
  3372. SmallVector<std::pair<OperatorNodeBase*, DepType>>>
  3373. readers;
  3374. static const ThinHashSet<Typeinfo*> opr_type_list = {
  3375. opr::TypeCvt::typeinfo(), opr::Dimshuffle::typeinfo(),
  3376. opr::Reshape::typeinfo(), opr::ConvBias::typeinfo()};
  3377. opt.graph().iter([&readers](OperatorNodeBase* opr) {
  3378. for (auto&& i : opr->node_prop().dep_map()) {
  3379. if (opr_type_list.count(i.first->owner_opr()->dyn_typeinfo())) {
  3380. readers[i.first->owner_opr()].emplace_back(opr, i.second);
  3381. }
  3382. }
  3383. });
  3384. auto rewriter = opt.graph().make_rewriter();
  3385. auto nchw42nchw = [](VarNode* inp) -> VarNode* {
  3386. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  3387. auto x = SymbolVar(inp);
  3388. auto xshp = opr::GetVarShape::make(x);
  3389. auto cv = [&x](int v) { return x.make_scalar(v); };
  3390. auto sub = [&xshp, &cv](int idx) {
  3391. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  3392. };
  3393. auto tshp = opr::Concat::make({sub(0), sub(1) * 4, sub(2), sub(3)}, 0);
  3394. auto y0 = opr::Dimshuffle::make(x, {0, 1, 4, 2, 3});
  3395. auto y1 = opr::Reshape::make(y0, tshp);
  3396. auto y2 = opr::TypeCvt::make(y1, dtype::Float32());
  3397. return y2.node();
  3398. };
  3399. auto nchw42nchw32 = [](VarNode* inp) -> VarNode* {
  3400. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 4);
  3401. auto x = SymbolVar(inp);
  3402. auto xshp = opr::GetVarShape::make(x);
  3403. auto cv = [&x](int v) { return x.make_scalar(v); };
  3404. auto sub = [&xshp, &cv](int idx) {
  3405. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  3406. };
  3407. auto tshp0 = opr::Concat::make(
  3408. {sub(0), sub(1) / 8, cv(8), sub(2), sub(3), sub(4)}, 0),
  3409. tshp1 = opr::Concat::make(
  3410. {sub(0), sub(1) / 8, sub(2), sub(3), sub(4) * 8}, 0);
  3411. auto y0 = opr::Reshape::make(x, tshp0);
  3412. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 3, 4, 2, 5});
  3413. auto y2 = opr::Reshape::make(y1, tshp1);
  3414. return y2.node();
  3415. };
  3416. auto nchw322nchw4 = [](VarNode* inp) -> VarNode* {
  3417. mgb_assert(inp->shape().ndim == 5 && inp->shape()[4] == 32);
  3418. auto x = SymbolVar(inp);
  3419. auto xshp = opr::GetVarShape::make(x);
  3420. auto cv = [&x](int v) { return x.make_scalar(v); };
  3421. auto sub = [&xshp, &cv](int idx) {
  3422. return opr::IndexAt::make(xshp, {{0, cv(idx)}});
  3423. };
  3424. auto tshp0 = opr::Concat::make(
  3425. {sub(0), sub(1), sub(2), sub(3), cv(8), sub(4) / 8}, 0),
  3426. tshp1 = opr::Concat::make(
  3427. {sub(0), sub(1) * 8, sub(2), sub(3), sub(4) / 8}, 0);
  3428. auto y0 = opr::Reshape::make(x, tshp0);
  3429. auto y1 = opr::Dimshuffle::make(y0, {0, 1, 4, 2, 3, 5});
  3430. auto y2 = opr::Reshape::make(y1, tshp1);
  3431. return y2.node();
  3432. };
  3433. auto try_conv_dimshuffle_reshape_typecvt = [&rewriter, &readers,
  3434. &nchw42nchw](
  3435. OperatorNodeBase* opr) {
  3436. ThinHashSet<OperatorNodeBase*> opr_set;
  3437. ThinHashSet<OperatorNodeBase*> reader_set;
  3438. // check typecvt
  3439. auto typecvt = try_cast_as_op<opr::TypeCvt>(opr);
  3440. if (typecvt == nullptr)
  3441. return false;
  3442. auto inp_dtype = typecvt->input(0)->dtype(),
  3443. out_dtype = typecvt->output(0)->dtype();
  3444. bool is_s82f32 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3445. out_dtype.enumv() == DTypeEnum::Float32;
  3446. if (!is_s82f32)
  3447. return false;
  3448. opr_set.insert(opr);
  3449. // check reshape
  3450. auto reshape =
  3451. try_cast_as_op<opr::Reshape>(typecvt->input(0)->owner_opr());
  3452. if (reshape == nullptr)
  3453. return false;
  3454. opr_set.insert(reshape);
  3455. for (auto&& i : readers[reshape]) {
  3456. if (i.second & DepType::DEV_VALUE) {
  3457. reader_set.insert(i.first);
  3458. }
  3459. }
  3460. // check shuffle
  3461. auto shuffle =
  3462. try_cast_as_op<opr::Dimshuffle>(reshape->input(0)->owner_opr());
  3463. if (shuffle == nullptr)
  3464. return false;
  3465. auto&& param = shuffle->param();
  3466. if (param.pattern_len != 5)
  3467. return false;
  3468. bool is_nchw42nchw = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3469. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  3470. param.pattern[4] == 3 &&
  3471. shuffle->input(0)->shape()[4] == 4;
  3472. if (!is_nchw42nchw)
  3473. return false;
  3474. opr_set.insert(shuffle);
  3475. for (auto&& i : readers[shuffle]) {
  3476. if (i.second & DepType::DEV_VALUE) {
  3477. reader_set.insert(i.first);
  3478. }
  3479. }
  3480. // check conv bias
  3481. auto conv_bias =
  3482. try_cast_as_op<opr::ConvBias>(shuffle->input(0)->owner_opr());
  3483. if (conv_bias == nullptr)
  3484. return false;
  3485. inp_dtype = conv_bias->input(0)->dtype();
  3486. bool is_s8nchw4 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3487. conv_bias->param().format ==
  3488. megdnn::param::ConvBias::Format::NCHW4;
  3489. if (!is_s8nchw4)
  3490. return false;
  3491. if (conv_bias->input().size() != 3)
  3492. return false;
  3493. opr_set.insert(conv_bias);
  3494. for (auto&& i : readers[conv_bias]) {
  3495. if (i.second & DepType::DEV_VALUE) {
  3496. reader_set.insert(i.first);
  3497. }
  3498. }
  3499. for (auto reader : reader_set) {
  3500. if (opr_set.count(reader) <= 0) {
  3501. return false;
  3502. }
  3503. }
  3504. auto src = rewriter.get_var(conv_bias->input(0)),
  3505. filter = rewriter.get_var(conv_bias->input(1)),
  3506. bias = rewriter.get_var(conv_bias->input(2));
  3507. auto new_bias = nchw42nchw(bias);
  3508. auto new_param = conv_bias->param();
  3509. new_param.format = megdnn::param::ConvBias::Format::NCHW4_NCHW;
  3510. auto conv_bias_shuffle = opr::ConvBias::make(
  3511. src, filter, new_bias, new_param, conv_bias->execution_policy(),
  3512. OperatorNodeConfig{dtype::Float32()});
  3513. rewriter.replace_var(opr->output(0), conv_bias_shuffle.node(),
  3514. mgb_cstr_log("replace conv_bias + typecvt + "
  3515. "dimshuffle + "
  3516. "reshape to conv_bias(NCHW4_NCHW)"));
  3517. return true;
  3518. };
  3519. auto try_conv_reformat_nchw42nchw32 = [&rewriter, &nchw42nchw32,
  3520. &readers](OperatorNodeBase* opr) {
  3521. ThinHashSet<OperatorNodeBase*> opr_set;
  3522. ThinHashSet<OperatorNodeBase*> reader_set;
  3523. // check reshape
  3524. auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
  3525. if (reshape1 == nullptr)
  3526. return false;
  3527. opr_set.insert(opr);
  3528. // check dimshuffle
  3529. auto shuffle = try_cast_as_op<opr::Dimshuffle>(
  3530. reshape1->input(0)->owner_opr());
  3531. if (shuffle == nullptr)
  3532. return false;
  3533. auto&& param = shuffle->param();
  3534. if (param.pattern_len != 6)
  3535. return false;
  3536. bool is_nchw42nchw32 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3537. param.pattern[2] == 3 && param.pattern[3] == 4 &&
  3538. param.pattern[4] == 2 && param.pattern[5] == 5 &&
  3539. shuffle->output(0)->shape()[5] == 4 &&
  3540. shuffle->output(0)->shape()[4] == 8;
  3541. if (!is_nchw42nchw32)
  3542. return false;
  3543. opr_set.insert(shuffle);
  3544. for (auto&& i : readers[shuffle]) {
  3545. if (i.second & DepType::DEV_VALUE) {
  3546. reader_set.insert(i.first);
  3547. }
  3548. }
  3549. // check reshape
  3550. auto reshape2 =
  3551. try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
  3552. if (reshape2 == nullptr)
  3553. return false;
  3554. opr_set.insert(reshape2);
  3555. for (auto&& i : readers[reshape2]) {
  3556. if (i.second & DepType::DEV_VALUE) {
  3557. reader_set.insert(i.first);
  3558. }
  3559. }
  3560. // check conv bias
  3561. auto conv_bias =
  3562. try_cast_as_op<opr::ConvBias>(reshape2->input(0)->owner_opr());
  3563. if (conv_bias == nullptr)
  3564. return false;
  3565. auto inp_dtype = conv_bias->input(0)->dtype();
  3566. bool is_s8nchw4 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3567. conv_bias->param().format ==
  3568. megdnn::param::ConvBias::Format::NCHW4;
  3569. if (!is_s8nchw4)
  3570. return false;
  3571. if (conv_bias->input().size() != 3)
  3572. return false;
  3573. opr_set.insert(conv_bias);
  3574. for (auto&& i : readers[conv_bias]) {
  3575. if (i.second & DepType::DEV_VALUE) {
  3576. reader_set.insert(i.first);
  3577. }
  3578. }
  3579. for (auto reader : reader_set) {
  3580. if (opr_set.count(reader) <= 0) {
  3581. return false;
  3582. }
  3583. }
  3584. auto src = rewriter.get_var(conv_bias->input(0)),
  3585. filter = rewriter.get_var(conv_bias->input(1)),
  3586. bias = rewriter.get_var(conv_bias->input(2));
  3587. auto new_bias = nchw42nchw32(bias);
  3588. auto new_param = conv_bias->param();
  3589. new_param.format = megdnn::param::ConvBias::Format::NCHW4_NCHW32;
  3590. auto conv_bias_shuffle = opr::ConvBias::make(
  3591. src, filter, new_bias, new_param, conv_bias->execution_policy(),
  3592. conv_bias->config());
  3593. rewriter.replace_var(
  3594. opr->output(0), conv_bias_shuffle.node(),
  3595. mgb_cstr_log("replace conv_bias + "
  3596. "reformat to conv_bias(NCHW4_NCHW32)"));
  3597. return true;
  3598. };
  3599. auto try_conv_reformat_nchw322nchw4 = [&rewriter, &readers, &nchw322nchw4](
  3600. OperatorNodeBase* opr) {
  3601. ThinHashSet<OperatorNodeBase*> opr_set;
  3602. ThinHashSet<OperatorNodeBase*> reader_set;
  3603. // check reshape
  3604. auto reshape1 = try_cast_as_op<opr::Reshape>(opr);
  3605. if (reshape1 == nullptr)
  3606. return false;
  3607. opr_set.insert(opr);
  3608. // check dimshuffle
  3609. auto shuffle = try_cast_as_op<opr::Dimshuffle>(
  3610. reshape1->input(0)->owner_opr());
  3611. if (shuffle == nullptr)
  3612. return false;
  3613. auto&& param = shuffle->param();
  3614. if (param.pattern_len != 6)
  3615. return false;
  3616. bool is_nchw322nchw4 = param.pattern[0] == 0 && param.pattern[1] == 1 &&
  3617. param.pattern[2] == 4 && param.pattern[3] == 2 &&
  3618. param.pattern[4] == 3 && param.pattern[5] == 5 &&
  3619. shuffle->input(0)->shape()[5] == 4 &&
  3620. shuffle->input(0)->shape()[4] == 8;
  3621. if (!is_nchw322nchw4)
  3622. return false;
  3623. opr_set.insert(shuffle);
  3624. for (auto&& i : readers[shuffle]) {
  3625. if (i.second & DepType::DEV_VALUE) {
  3626. reader_set.insert(i.first);
  3627. }
  3628. }
  3629. // check reshape
  3630. auto reshape2 =
  3631. try_cast_as_op<opr::Reshape>(shuffle->input(0)->owner_opr());
  3632. if (reshape2 == nullptr)
  3633. return false;
  3634. opr_set.insert(reshape2);
  3635. for (auto&& i : readers[reshape2]) {
  3636. if (i.second & DepType::DEV_VALUE) {
  3637. reader_set.insert(i.first);
  3638. }
  3639. }
  3640. // check conv bias
  3641. auto conv_bias =
  3642. try_cast_as_op<opr::ConvBias>(reshape2->input(0)->owner_opr());
  3643. if (conv_bias == nullptr)
  3644. return false;
  3645. auto inp_dtype = conv_bias->input(0)->dtype();
  3646. bool is_s8nchw32 = inp_dtype.enumv() == DTypeEnum::QuantizedS8 &&
  3647. conv_bias->param().format ==
  3648. megdnn::param::ConvBias::Format::NCHW32;
  3649. if (!is_s8nchw32)
  3650. return false;
  3651. if (conv_bias->input().size() != 3)
  3652. return false;
  3653. opr_set.insert(conv_bias);
  3654. for (auto&& i : readers[conv_bias]) {
  3655. if (i.second & DepType::DEV_VALUE) {
  3656. reader_set.insert(i.first);
  3657. }
  3658. }
  3659. for (auto reader : reader_set) {
  3660. if (opr_set.count(reader) <= 0) {
  3661. return false;
  3662. }
  3663. }
  3664. auto src = rewriter.get_var(conv_bias->input(0)),
  3665. filter = rewriter.get_var(conv_bias->input(1)),
  3666. bias = rewriter.get_var(conv_bias->input(2));
  3667. auto new_bias = nchw322nchw4(bias);
  3668. auto new_param = conv_bias->param();
  3669. new_param.format = megdnn::param::ConvBias::Format::NCHW32_NCHW4;
  3670. auto conv_bias_shuffle = opr::ConvBias::make(
  3671. src, filter, new_bias, new_param, conv_bias->execution_policy(),
  3672. conv_bias->config());
  3673. rewriter.replace_var(
  3674. opr->output(0), conv_bias_shuffle.node(),
  3675. mgb_cstr_log("replace conv_bias + "
  3676. "reformat to conv_bias(NCHW32_NCHW4)"));
  3677. return true;
  3678. };
  3679. MGB_MARK_USED_VAR(try_conv_reformat_nchw322nchw4);
  3680. auto on_opr = [&try_conv_dimshuffle_reshape_typecvt,
  3681. &try_conv_reformat_nchw42nchw32,
  3682. #if CUDA_VERSION >= 10020
  3683. &try_conv_reformat_nchw322nchw4,
  3684. #endif
  3685. &rewriter](OperatorNodeBase* opr) {
  3686. if (!try_conv_dimshuffle_reshape_typecvt(opr) &&
  3687. !try_conv_reformat_nchw42nchw32(opr)
  3688. #if CUDA_VERSION >= 10020
  3689. && !try_conv_reformat_nchw322nchw4(opr)
  3690. #endif
  3691. ) {
  3692. rewriter.auto_replace_outputs(opr);
  3693. }
  3694. };
  3695. opt.graph().iter(on_opr);
  3696. rewriter.apply_inplace();
  3697. MIDOUT_E
  3698. }
  3699. /* ==================== PaddingChannelPass ================= */
  3700. const char* PaddingChannelPass::name() const {
  3701. return mgb_cstr_log("padding output channel to multiple of 4/32");
  3702. }
  3703. void PaddingChannelPass::apply(OptState& opt) const {
  3704. MIDOUT_B("PaddingChannelPass::apply");
  3705. // do not check shape
  3706. opt.set_var_replace_check_flag(VarReplaceCheckFlag::CHECK_ALL ^
  3707. VarReplaceCheckFlag::CHECK_SHAPE);
  3708. ThinHashSet<OperatorNodeBase*> padding_oprs;
  3709. ThinHashMap<Typeinfo*, thin_function<OperatorNodeBase*(
  3710. OperatorNodeBase*, const VarNodeArray&)>>
  3711. opr_replace_funcs;
  3712. auto rewriter = opt.graph().make_rewriter();
  3713. auto pad_in_channels = [](VarNode* inp, size_t pad_channels) -> VarNode* {
  3714. mgb_assert(inp->shape().ndim == 4);
  3715. mgb_assert(inp->dtype().enumv() == DTypeEnum::QuantizedS4 ||
  3716. inp->dtype().enumv() == DTypeEnum::Quantized4Asymm ||
  3717. inp->dtype().enumv() == DTypeEnum::QuantizedS8 ||
  3718. inp->dtype().enumv() == DTypeEnum::QuantizedS32);
  3719. TensorShape shape{inp->shape()[0], pad_channels, inp->shape()[2],
  3720. inp->shape()[3]};
  3721. std::shared_ptr<HostTensorND> host_val =
  3722. std::make_shared<HostTensorND>(inp->comp_node(), inp->dtype());
  3723. host_val->resize(shape);
  3724. auto ptr = host_val->raw_ptr();
  3725. size_t size_bytes =
  3726. TensorLayout{shape, inp->dtype()}.span().dist_byte();
  3727. std::memset(ptr, 0, size_bytes);
  3728. auto padding =
  3729. opr::ImmutableTensor::make(*inp->owner_graph(), *host_val);
  3730. auto out = opr::Concat::make({inp, padding}, 1);
  3731. return out.node();
  3732. };
  3733. auto pad_out_channels = [](VarNode* inp, size_t pad_channels) -> VarNode* {
  3734. mgb_assert(inp->shape().ndim == 4);
  3735. mgb_assert(inp->dtype().enumv() == DTypeEnum::QuantizedS4 ||
  3736. inp->dtype().enumv() == DTypeEnum::Quantized4Asymm ||
  3737. inp->dtype().enumv() == DTypeEnum::QuantizedS8 ||
  3738. inp->dtype().enumv() == DTypeEnum::QuantizedS32);
  3739. TensorShape shape{pad_channels, inp->shape()[1], inp->shape()[2],
  3740. inp->shape()[3]};
  3741. std::shared_ptr<HostTensorND> host_val =
  3742. std::make_shared<HostTensorND>(inp->comp_node(), inp->dtype());
  3743. host_val->resize(shape);
  3744. auto ptr = host_val->raw_ptr();
  3745. size_t size_bytes =
  3746. TensorLayout{shape, inp->dtype()}.span().dist_byte();
  3747. std::memset(ptr, 0, size_bytes);
  3748. auto padding =
  3749. opr::ImmutableTensor::make(*inp->owner_graph(), *host_val);
  3750. auto out = opr::Concat::make({inp, padding}, 0);
  3751. return out.node();
  3752. };
  3753. auto extract_subtensor = [](VarNode* inp,
  3754. const TensorShape& orig_shape) -> VarNode* {
  3755. mgb_assert(inp->shape().ndim == 4);
  3756. mgb_assert(inp->shape()[0] == orig_shape[0]);
  3757. mgb_assert(inp->shape()[2] == orig_shape[2]);
  3758. mgb_assert(inp->shape()[3] == orig_shape[3]);
  3759. size_t orig_channels = orig_shape[1];
  3760. auto x = SymbolVar(inp);
  3761. auto cv = [&x](int v) { return x.make_scalar(v); };
  3762. using AIdx = opr::Subtensor::AxisIndexer;
  3763. auto sub = opr::Subtensor::make(
  3764. x, {AIdx::make_interval(0, None, None, cv(1)),
  3765. AIdx::make_interval(1, None, cv(orig_channels), None),
  3766. AIdx::make_interval(2, None, None, cv(1)),
  3767. AIdx::make_interval(3, None, None, cv(1))});
  3768. return sub.node();
  3769. };
  3770. // padding policy for conv bias with data type qint8
  3771. auto padding_policy_qint8 = [&padding_oprs, &pad_in_channels,
  3772. &pad_out_channels](
  3773. OperatorNodeBase* opr,
  3774. const VarNodeArray& new_inp) {
  3775. mgb_assert(opr->input().size() == new_inp.size());
  3776. mgb_assert(new_inp.size() == 3);
  3777. mgb_assert(opr->input(1)->shape().eq_shape(new_inp[1]->shape()));
  3778. auto inps = new_inp;
  3779. size_t out_channels = opr->input(1)->shape()[0];
  3780. size_t in_channels = opr->input(1)->shape()[1];
  3781. size_t new_in_channels = new_inp[0]->shape()[1];
  3782. // pad input channels
  3783. if (padding_oprs.count(opr->input(0)->owner_opr())) {
  3784. size_t pad_channels = new_in_channels - in_channels;
  3785. inps[1] = pad_in_channels(new_inp[1], pad_channels);
  3786. } else {
  3787. size_t pad_channels = 0;
  3788. mgb_assert(new_in_channels == in_channels);
  3789. if (in_channels <= 16) {
  3790. if (in_channels % 4)
  3791. pad_channels = 4 - (in_channels % 4); // pad to use dp4a
  3792. } else {
  3793. if (in_channels % 32)
  3794. pad_channels =
  3795. 32 - (in_channels % 32); // pad to use tensorcore
  3796. }
  3797. if (pad_channels > 0) {
  3798. inps[0] = pad_in_channels(new_inp[0], pad_channels);
  3799. inps[1] = pad_in_channels(new_inp[1], pad_channels);
  3800. }
  3801. }
  3802. out_channels = inps[1]->shape()[0];
  3803. in_channels = inps[1]->shape()[1];
  3804. size_t pad_channels = 0;
  3805. if (out_channels <= 16) {
  3806. if (out_channels % 4)
  3807. pad_channels = 4 - (out_channels % 4);
  3808. } else {
  3809. if (out_channels % 32)
  3810. pad_channels = 32 - (out_channels % 32);
  3811. }
  3812. if (pad_channels > 0) {
  3813. inps[1] = pad_out_channels(inps[1], pad_channels);
  3814. inps[2] = pad_in_channels(inps[2], pad_channels);
  3815. padding_oprs.insert(opr);
  3816. }
  3817. return serialization::copy_opr_shallow(*opr, inps, opr->config());
  3818. };
  3819. // padding policy for conv bias with data type qint4 and quint4
  3820. auto padding_policy_int4 = [&padding_oprs, &pad_in_channels,
  3821. &pad_out_channels](
  3822. OperatorNodeBase* opr,
  3823. const VarNodeArray& new_inp) {
  3824. mgb_assert(opr->input().size() == new_inp.size());
  3825. mgb_assert(new_inp.size() == 3);
  3826. mgb_assert(opr->input(1)->shape().eq_shape(new_inp[1]->shape()));
  3827. auto inps = new_inp;
  3828. size_t out_channels = opr->input(1)->shape()[0];
  3829. size_t in_channels = opr->input(1)->shape()[1];
  3830. size_t new_in_channels = new_inp[0]->shape()[1];
  3831. // pad input channels
  3832. if (padding_oprs.count(opr->input(0)->owner_opr())) {
  3833. if (new_in_channels % 64 == 0) {
  3834. size_t pad_channels = new_in_channels - in_channels;
  3835. inps[1] = pad_in_channels(new_inp[1], pad_channels);
  3836. } else {
  3837. size_t pad_channels_0 = 64 - (new_in_channels % 64);
  3838. size_t pad_channels_1 = 64 - (in_channels % 64);
  3839. inps[0] = pad_in_channels(new_inp[0], pad_channels_0);
  3840. inps[1] = pad_in_channels(new_inp[1], pad_channels_1);
  3841. }
  3842. } else {
  3843. size_t pad_channels = 0;
  3844. mgb_assert(new_in_channels == in_channels);
  3845. if (in_channels % 64)
  3846. pad_channels = 64 - (in_channels % 64);
  3847. if (pad_channels > 0) {
  3848. inps[0] = pad_in_channels(new_inp[0], pad_channels);
  3849. inps[1] = pad_in_channels(new_inp[1], pad_channels);
  3850. }
  3851. }
  3852. out_channels = inps[1]->shape()[0];
  3853. in_channels = inps[1]->shape()[1];
  3854. size_t pad_channels = 0;
  3855. if (out_channels % 64)
  3856. pad_channels = 64 - (out_channels % 64);
  3857. if (pad_channels > 0) {
  3858. inps[1] = pad_out_channels(inps[1], pad_channels);
  3859. inps[2] = pad_in_channels(inps[2], pad_channels);
  3860. padding_oprs.insert(opr);
  3861. }
  3862. return serialization::copy_opr_shallow(*opr, inps, opr->config());
  3863. };
  3864. opr_replace_funcs[opr::ConvBiasForward::typeinfo()] =
  3865. [&padding_oprs, &padding_policy_qint8, &padding_policy_int4](
  3866. OperatorNodeBase* opr, const VarNodeArray& new_inp) {
  3867. if (opr->input(0)->dtype().enumv() == DTypeEnum::QuantizedS8) {
  3868. return padding_policy_qint8(opr, new_inp);
  3869. } else if (opr->input(0)->dtype().enumv() ==
  3870. DTypeEnum::QuantizedS4 ||
  3871. opr->input(0)->dtype().enumv() ==
  3872. DTypeEnum::Quantized4Asymm) {
  3873. return padding_policy_int4(opr, new_inp);
  3874. } else {
  3875. mgb_assert(
  3876. padding_oprs.count(opr->input(0)->owner_opr()) == 0,
  3877. "conv bias operator for data type(%s) cannot be "
  3878. "padded channel. "
  3879. "consumer(%s), producer(%s)",
  3880. opr->input(0)->dtype().name(), opr->cname(),
  3881. opr->input(0)->owner_opr()->cname());
  3882. return serialization::copy_opr_shallow(*opr, new_inp,
  3883. opr->config());
  3884. }
  3885. };
  3886. opr_replace_funcs[opr::ConvolutionBackwardData::typeinfo()] =
  3887. [&padding_oprs, &pad_in_channels, &pad_out_channels](
  3888. OperatorNodeBase* opr, const VarNodeArray& new_inp) {
  3889. if (opr->input(1)->dtype().enumv() != DTypeEnum::QuantizedS8) {
  3890. mgb_assert(
  3891. padding_oprs.count(opr->input(0)->owner_opr()) == 0,
  3892. "conv bwd data operator for data type(%s) cannot "
  3893. "be "
  3894. "padded channel. "
  3895. "consumer(%s), producer(%s)",
  3896. opr->input(0)->dtype().name(), opr->cname(),
  3897. opr->input(0)->owner_opr()->cname());
  3898. return serialization::copy_opr_shallow(*opr, new_inp,
  3899. opr->config());
  3900. }
  3901. mgb_assert(opr->input().size() == new_inp.size());
  3902. mgb_assert(new_inp.size() == 2,
  3903. "deconv (conv bwd data) operator for inference can "
  3904. "only have 2 input vars(got:%zu)",
  3905. new_inp.size());
  3906. mgb_assert(
  3907. opr->input(0)->shape().eq_shape(new_inp[0]->shape()));
  3908. auto inps = new_inp;
  3909. size_t out_channels = opr->input(0)->shape()[0];
  3910. size_t in_channels = opr->input(0)->shape()[1];
  3911. size_t new_out_channels = new_inp[1]->shape()[1];
  3912. // pad output channels
  3913. if (padding_oprs.count(opr->input(1)->owner_opr())) {
  3914. size_t pad_channels = new_out_channels - out_channels;
  3915. inps[0] = pad_out_channels(new_inp[0], pad_channels);
  3916. } else {
  3917. size_t pad_channels = 0;
  3918. if (out_channels % 4)
  3919. pad_channels = 4 - (out_channels % 4);
  3920. if (pad_channels > 0) {
  3921. inps[0] = pad_out_channels(new_inp[0], pad_channels);
  3922. inps[1] = pad_in_channels(new_inp[1], pad_channels);
  3923. }
  3924. }
  3925. out_channels = inps[0]->shape()[0];
  3926. in_channels = inps[0]->shape()[1];
  3927. // pad input channels
  3928. size_t pad_channels = 0;
  3929. if (in_channels % 4)
  3930. pad_channels = 4 - (in_channels % 4);
  3931. if (pad_channels > 0) {
  3932. inps[0] = pad_in_channels(inps[0], pad_channels);
  3933. padding_oprs.insert(opr);
  3934. }
  3935. return serialization::copy_opr_shallow(*opr, inps,
  3936. opr->config());
  3937. };
  3938. auto replace_format_aware_opr = [&padding_oprs](
  3939. OperatorNodeBase* opr,
  3940. const VarNodeArray& new_inp) {
  3941. if (opr->input(0)->dtype().enumv() != DTypeEnum::QuantizedS8 &&
  3942. opr->input(0)->dtype().enumv() != DTypeEnum::QuantizedS4 &&
  3943. opr->input(0)->dtype().enumv() != DTypeEnum::Quantized4Asymm) {
  3944. mgb_assert(padding_oprs.count(opr->input(0)->owner_opr()) == 0,
  3945. "operator(type:%s,name:%s) for data type(%s) cannot be "
  3946. "padded channel. extra info:"
  3947. "consumer(%s), producer(%s)",
  3948. opr->dyn_typeinfo()->name, opr->cname(),
  3949. opr->input(0)->dtype().name(), opr->cname(),
  3950. opr->input(0)->owner_opr()->cname());
  3951. return serialization::copy_opr_shallow(*opr, new_inp,
  3952. opr->config());
  3953. }
  3954. mgb_assert(opr->input().size() == new_inp.size());
  3955. if (padding_oprs.count(opr->input(0)->owner_opr())) {
  3956. padding_oprs.insert(opr);
  3957. }
  3958. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  3959. };
  3960. opr_replace_funcs[opr::PoolingForward::typeinfo()] =
  3961. replace_format_aware_opr;
  3962. opr_replace_funcs[opr::WarpPerspectiveForward::typeinfo()] =
  3963. replace_format_aware_opr;
  3964. auto replace_elemwise_like_opr = [&padding_oprs, &extract_subtensor](
  3965. OperatorNodeBase* opr,
  3966. const VarNodeArray& new_inp) {
  3967. mgb_assert(opr->input().size() == new_inp.size());
  3968. bool have_padding_inp = false;
  3969. bool padding_all_inps = true;
  3970. bool same_padding = true;
  3971. size_t channels_after_padding = 0;
  3972. size_t i = 0;
  3973. for (auto&& cur_inp : opr->input()) {
  3974. bool padding_cur_inp = padding_oprs.count(cur_inp->owner_opr()) > 0;
  3975. if (padding_cur_inp) {
  3976. if (!have_padding_inp)
  3977. have_padding_inp = true;
  3978. if (channels_after_padding == 0) {
  3979. channels_after_padding = new_inp[i]->shape()[1];
  3980. } else {
  3981. same_padding =
  3982. channels_after_padding == new_inp[i]->shape()[1];
  3983. }
  3984. }
  3985. if (padding_all_inps && (!padding_cur_inp || !same_padding))
  3986. padding_all_inps = false;
  3987. ++i;
  3988. }
  3989. if (have_padding_inp && !padding_all_inps) {
  3990. auto inps = new_inp;
  3991. for (size_t i = 0; i < new_inp.size(); ++i) {
  3992. auto cur_inp = opr->input(i);
  3993. bool padding_cur_inp =
  3994. padding_oprs.count(cur_inp->owner_opr()) > 0;
  3995. if (padding_cur_inp) {
  3996. inps[i] = extract_subtensor(inps[i], cur_inp->shape());
  3997. }
  3998. }
  3999. return serialization::copy_opr_shallow(*opr, inps, opr->config());
  4000. }
  4001. if (padding_all_inps) {
  4002. padding_oprs.insert(opr);
  4003. }
  4004. return serialization::copy_opr_shallow(*opr, new_inp, opr->config());
  4005. };
  4006. opr_replace_funcs[opr::ElemwiseMultiType::typeinfo()] =
  4007. replace_elemwise_like_opr;
  4008. opr_replace_funcs[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
  4009. opr_replace_funcs[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
  4010. auto replace_nonpadding_oprs = [&padding_oprs, &extract_subtensor](
  4011. OperatorNodeBase* opr,
  4012. const VarNodeArray& new_inp) {
  4013. mgb_assert(opr->input().size() == new_inp.size());
  4014. auto inps = new_inp;
  4015. for (size_t i = 0; i < new_inp.size(); ++i) {
  4016. auto cur_inp = opr->input(i);
  4017. bool padding_cur_inp = padding_oprs.count(cur_inp->owner_opr()) > 0;
  4018. if (padding_cur_inp) {
  4019. inps[i] = extract_subtensor(inps[i], cur_inp->shape());
  4020. }
  4021. }
  4022. return serialization::copy_opr_shallow(*opr, inps, opr->config());
  4023. };
  4024. opr_replace_funcs[opr::Reshape::typeinfo()] = replace_nonpadding_oprs;
  4025. opr_replace_funcs[opr::GetVarShape::typeinfo()] = replace_nonpadding_oprs;
  4026. opr_replace_funcs[opr::Concat::typeinfo()] = replace_nonpadding_oprs;
  4027. opr_replace_funcs[opr::Reduce::typeinfo()] = replace_nonpadding_oprs;
  4028. opr_replace_funcs[opr::Subtensor::typeinfo()] = replace_nonpadding_oprs;
  4029. auto on_opr = [&opt, &rewriter, &opr_replace_funcs,
  4030. &extract_subtensor](OperatorNodeBase* opr) {
  4031. auto it = opr_replace_funcs.find(opr->dyn_typeinfo());
  4032. if (it != opr_replace_funcs.end()) {
  4033. VarNodeArray new_inp;
  4034. new_inp.reserve(opr->input().size());
  4035. for (auto&& inp : opr->input()) {
  4036. new_inp.push_back(rewriter.get_var(inp));
  4037. }
  4038. auto new_opr = (it->second)(opr, new_inp);
  4039. auto &&out0 = opr->output(), &&out1 = new_opr->output();
  4040. mgb_assert(out0.size() == out1.size(),
  4041. "bad opr replace: src=%s{%s} dst=%s{%s}, "
  4042. "src.size=%zu "
  4043. "dst.size=%zu",
  4044. opr->cname(), opr->dyn_typeinfo()->name,
  4045. new_opr->cname(), new_opr->dyn_typeinfo()->name,
  4046. out0.size(), out1.size());
  4047. for (size_t i = 0; i < out0.size(); ++i) {
  4048. if (!out0[i]->contain_flag(VarNode::Flag::VOLATILE_CONTENT)) {
  4049. mgb_assert(!out1[i]->contain_flag(
  4050. VarNode::Flag::VOLATILE_CONTENT));
  4051. auto src = out0[i];
  4052. auto dst = out1[i];
  4053. if (opt.graph().endpoint_contain(src) &&
  4054. !src->shape().eq_shape(dst->shape())) {
  4055. dst = extract_subtensor(dst, src->shape());
  4056. }
  4057. rewriter.replace_var(src, dst, nullptr);
  4058. }
  4059. }
  4060. } else {
  4061. rewriter.auto_replace_outputs(opr);
  4062. }
  4063. };
  4064. opt.graph().iter(on_opr);
  4065. rewriter.apply_inplace();
  4066. MIDOUT_E
  4067. }
  4068. /* ================ EnableNCHW64Pass =============== */
  4069. VarNode* EnableNCHW64Pass::on_graph_endpoint_var(VarNode* new_var,
  4070. VarNode* orig_var) const {
  4071. if (!orig_var->shape().eq_shape(new_var->shape())) {
  4072. auto iter = m_opr_format_map.find(new_var->owner_opr());
  4073. mgb_assert(iter != m_opr_format_map.end(),
  4074. "cannot find opr(type:%s,name:%s) information, related "
  4075. "output var node(name:%s)",
  4076. new_var->owner_opr()->dyn_typeinfo()->name,
  4077. new_var->owner_opr()->cname(), new_var->cname());
  4078. const auto& fmt = iter->second;
  4079. using LayoutType = RelayoutPlaceholder::LayoutType;
  4080. LayoutType type;
  4081. switch (fmt) {
  4082. case Format::NCHW4:
  4083. type = LayoutType::NCHW4_TO_NCHW;
  4084. break;
  4085. case Format::NCHW32:
  4086. type = LayoutType::NCHW32_TO_NCHW;
  4087. break;
  4088. case Format::NCHW64:
  4089. type = LayoutType::NCHW64_TO_NCHW;
  4090. break;
  4091. default:
  4092. mgb_throw(AssertionError,
  4093. "format(%d) is not supported, related var "
  4094. "node(name:%s)",
  4095. static_cast<int>(fmt), orig_var->cname());
  4096. };
  4097. return RelayoutPlaceholder::make(new_var, type).node();
  4098. }
  4099. return new_var;
  4100. }
  4101. std::unique_ptr<EnableNCHW64Pass>
  4102. EnableNCHW64Pass::make_nchw64_converter() {
  4103. MIDOUT_B("EnableNCHW64Pass::make")
  4104. auto ret = std::make_unique<EnableNCHW64Pass>();
  4105. ret->set_var_replace_check_flag(VarReplaceCheckFlag::CHECK_ALL ^
  4106. VarReplaceCheckFlag::CHECK_SHAPE);
  4107. auto& replace_func = ret->m_opr_replace_func;
  4108. auto& format_map = ret->m_opr_format_map;
  4109. auto make_new_conv = [](const VarNodeArray& inps,
  4110. const opr::ConvBiasForward* orig_conv,
  4111. Format format) {
  4112. auto param = orig_conv->param();
  4113. // change format
  4114. param.format = format;
  4115. if (inps.size() == 2) {
  4116. auto new_conv = opr::ConvBiasForward::make(
  4117. inps[0], inps[1], param, orig_conv->execution_policy(),
  4118. orig_conv->config());
  4119. return new_conv.node();
  4120. } else if (inps.size() == 3) {
  4121. auto new_conv = opr::ConvBiasForward::make(
  4122. inps[0], inps[1], inps[2], param,
  4123. orig_conv->execution_policy(), orig_conv->config());
  4124. return new_conv.node();
  4125. } else {
  4126. mgb_assert(inps.size() == 4);
  4127. auto new_conv = opr::ConvBiasForward::make(
  4128. inps[0], inps[1], inps[2], inps[3], param,
  4129. orig_conv->execution_policy(), orig_conv->config());
  4130. return new_conv.node();
  4131. }
  4132. };
  4133. auto try_transform_to_nchw =
  4134. [&format_map](
  4135. OperatorNodeBase* opr,
  4136. const VarNodeArray& new_inp) -> VarNode* {
  4137. mgb_assert(opr->input().size()==new_inp.size());
  4138. bool check_dtype =
  4139. new_inp[0]->dtype().enumv() == DTypeEnum::Float32 &&
  4140. new_inp[1]->dtype().enumv() == DTypeEnum::Float32;
  4141. if (opr->input().size() >= 3)
  4142. check_dtype &=
  4143. new_inp[2]->dtype().enumv() == DTypeEnum::Float32;
  4144. if (opr->input().size() >= 4)
  4145. check_dtype &=
  4146. new_inp[3]->dtype().enumv() == DTypeEnum::Float32;
  4147. if (!check_dtype)
  4148. return nullptr;
  4149. auto inps = new_inp;
  4150. auto process = [&](size_t i) -> VarNode* {
  4151. auto iter = format_map.find(new_inp[i]->owner_opr());
  4152. if (iter == format_map.end()) {
  4153. return inps[i];
  4154. } else {
  4155. const auto& fmt = iter->second;
  4156. if (fmt == Format::NCHW32) {
  4157. auto ovar = RelayoutPlaceholder::make(
  4158. inps[i],
  4159. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW);
  4160. return ovar.node();
  4161. } else if (fmt == Format::NCHW4) {
  4162. auto ovar = RelayoutPlaceholder::make(
  4163. inps[i],
  4164. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW);
  4165. return ovar.node();
  4166. } else {
  4167. mgb_assert(fmt == Format::NCHW64);
  4168. auto ovar = RelayoutPlaceholder::make(
  4169. inps[i],
  4170. RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW);
  4171. return ovar.node();
  4172. }
  4173. }
  4174. };
  4175. for (size_t i = 0; i < inps.size(); ++i) {
  4176. inps[i] = process(i);
  4177. }
  4178. auto ret = serialization::copy_opr_shallow(*opr, inps, opr->config());
  4179. return ret->output()[0];
  4180. };
  4181. auto try_transform_to_nchw4 =
  4182. [make_new_conv, &format_map](
  4183. OperatorNodeBase* opr,
  4184. const VarNodeArray& new_inp) -> VarNode* {
  4185. mgb_assert(opr->input().size()==new_inp.size());
  4186. bool check_dtype =
  4187. new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8 &&
  4188. new_inp[1]->dtype().enumv() == DTypeEnum::QuantizedS8;
  4189. mgb_assert(opr->output().size() > 0);
  4190. bool dst_float = opr->output(0)->dtype().enumv() == DTypeEnum::Float32;
  4191. if (opr->input().size() >= 3) {
  4192. auto dtype_expect = dst_float ? DTypeEnum::Float32
  4193. : DTypeEnum::QuantizedS32;
  4194. check_dtype &= new_inp[2]->dtype().enumv() == dtype_expect;
  4195. }
  4196. if (opr->input().size() >= 4) {
  4197. check_dtype &= new_inp[3]->dtype().enumv() ==
  4198. opr->output(0)->dtype().enumv();
  4199. }
  4200. if (!check_dtype)
  4201. return nullptr;
  4202. size_t out_channels = opr->input(1)->shape()[0];
  4203. size_t in_channels = opr->input(1)->shape()[1];
  4204. bool check_channels = out_channels % 4 == 0 && in_channels % 4 == 0;
  4205. mgb_assert(check_channels,
  4206. "invalid quantize conv bias opr(name:%s,oc:%zu,ic:%zu)",
  4207. opr->cname(), out_channels, in_channels);
  4208. auto inps = new_inp;
  4209. auto process = [&](size_t i) -> VarNode* {
  4210. auto iter = format_map.find(new_inp[i]->owner_opr());
  4211. if (iter == format_map.end()) {
  4212. auto ovar = RelayoutPlaceholder::make(
  4213. inps[i],
  4214. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4);
  4215. return ovar.node();
  4216. } else {
  4217. const auto& fmt = iter->second;
  4218. if (fmt == Format::NCHW4) {
  4219. return inps[i];
  4220. } else if (fmt == Format::NCHW32) {
  4221. auto ovar = RelayoutPlaceholder::make(
  4222. inps[i],
  4223. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW4);
  4224. return ovar.node();
  4225. } else {
  4226. mgb_assert(fmt == Format::NCHW64);
  4227. auto ovar = RelayoutPlaceholder::make(
  4228. inps[i],
  4229. RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW4);
  4230. return ovar.node();
  4231. }
  4232. }
  4233. };
  4234. for (size_t i = 0; i < inps.size(); ++i) {
  4235. // do not format bias and z when dst_float is true
  4236. bool skip = dst_float && i >= 2;
  4237. if (!skip) inps[i] = process(i);
  4238. }
  4239. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  4240. auto ret = make_new_conv(
  4241. inps, &conv_bias,
  4242. dst_float ? Format::NCHW4_NCHW : Format::NCHW4);
  4243. if (!dst_float)
  4244. format_map.insert(std::make_pair(ret->owner_opr(), Format::NCHW4));
  4245. return ret;
  4246. };
  4247. auto try_transform_to_nchw32 =
  4248. [make_new_conv, &format_map](
  4249. OperatorNodeBase* opr,
  4250. const VarNodeArray& new_inp) -> VarNode* {
  4251. mgb_assert(opr->input().size()==new_inp.size());
  4252. bool check_dtype =
  4253. new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8 &&
  4254. new_inp[1]->dtype().enumv() == DTypeEnum::QuantizedS8;
  4255. if (opr->input().size() >= 3)
  4256. check_dtype &=
  4257. new_inp[2]->dtype().enumv() == DTypeEnum::QuantizedS32;
  4258. if (opr->input().size() >= 4)
  4259. check_dtype &=
  4260. new_inp[3]->dtype().enumv() == DTypeEnum::QuantizedS8;
  4261. if (!check_dtype)
  4262. return nullptr;
  4263. size_t out_channels = opr->input(1)->shape()[0];
  4264. size_t in_channels = opr->input(1)->shape()[1];
  4265. bool check_channels = out_channels % 32 == 0 && in_channels % 32 == 0;
  4266. if (!check_channels)
  4267. return nullptr;
  4268. auto inps = new_inp;
  4269. auto process = [&](size_t i) -> VarNode* {
  4270. auto iter = format_map.find(new_inp[i]->owner_opr());
  4271. if (iter == format_map.end()) {
  4272. auto ovar = RelayoutPlaceholder::make(
  4273. inps[i],
  4274. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW32);
  4275. return ovar.node();
  4276. } else {
  4277. const auto& fmt = iter->second;
  4278. if (fmt == Format::NCHW32) {
  4279. return inps[i];
  4280. } else if (fmt == Format::NCHW4) {
  4281. auto ovar = RelayoutPlaceholder::make(
  4282. inps[i],
  4283. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW32);
  4284. return ovar.node();
  4285. } else {
  4286. mgb_assert(fmt == Format::NCHW64);
  4287. auto ovar = RelayoutPlaceholder::make(
  4288. inps[i],
  4289. RelayoutPlaceholder::LayoutType::NCHW64_TO_NCHW32);
  4290. return ovar.node();
  4291. }
  4292. }
  4293. };
  4294. for (size_t i = 0; i < inps.size(); ++i) {
  4295. inps[i] = process(i);
  4296. }
  4297. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  4298. auto ret = make_new_conv(inps, &conv_bias, Format::NCHW32);
  4299. format_map.insert(std::make_pair(ret->owner_opr(), Format::NCHW32));
  4300. return ret;
  4301. };
  4302. auto try_transform_to_nchw64 =
  4303. [make_new_conv, &format_map](
  4304. OperatorNodeBase* opr,
  4305. const VarNodeArray& new_inp) -> VarNode* {
  4306. // fint4XWint4 and fuint4XWint4
  4307. mgb_assert(opr->input().size()==new_inp.size());
  4308. bool check_dtype =
  4309. (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS4 ||
  4310. new_inp[0]->dtype().enumv() ==
  4311. DTypeEnum::Quantized4Asymm) &&
  4312. new_inp[1]->dtype().enumv() == DTypeEnum::QuantizedS4;
  4313. if (opr->input().size() >= 3)
  4314. check_dtype &=
  4315. new_inp[2]->dtype().enumv() == DTypeEnum::QuantizedS32;
  4316. if (opr->input().size() >= 4)
  4317. check_dtype &= new_inp[3]->dtype().enumv() ==
  4318. new_inp[0]->dtype().enumv();
  4319. if (!check_dtype)
  4320. return nullptr;
  4321. size_t out_channels = opr->input(1)->shape()[0];
  4322. size_t in_channels = opr->input(1)->shape()[1];
  4323. bool check_channels = out_channels % 64 == 0 && in_channels % 64 == 0;
  4324. if (!check_channels)
  4325. return nullptr;
  4326. auto inps = new_inp;
  4327. auto process = [&](size_t i) -> VarNode* {
  4328. auto iter = format_map.find(new_inp[i]->owner_opr());
  4329. if (iter == format_map.end()) {
  4330. auto ovar = RelayoutPlaceholder::make(
  4331. inps[i],
  4332. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW64);
  4333. return ovar.node();
  4334. } else {
  4335. const auto& fmt = iter->second;
  4336. if (fmt == Format::NCHW64) {
  4337. return inps[i];
  4338. } else if (fmt == Format::NCHW4) {
  4339. auto ovar = RelayoutPlaceholder::make(
  4340. inps[i],
  4341. RelayoutPlaceholder::LayoutType::NCHW4_TO_NCHW64);
  4342. return ovar.node();
  4343. } else {
  4344. mgb_assert(fmt == Format::NCHW32);
  4345. auto ovar = RelayoutPlaceholder::make(
  4346. inps[i],
  4347. RelayoutPlaceholder::LayoutType::NCHW32_TO_NCHW64);
  4348. return ovar.node();
  4349. }
  4350. }
  4351. };
  4352. for (size_t i = 0; i < inps.size(); ++i) {
  4353. inps[i] = process(i);
  4354. }
  4355. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  4356. auto ret = make_new_conv(inps, &conv_bias, Format::NCHW64);
  4357. format_map.insert(std::make_pair(ret->owner_opr(), Format::NCHW64));
  4358. return ret;
  4359. };
  4360. // replace rule for conv bias opr
  4361. auto replace_conv_bias_opr = [&format_map, try_transform_to_nchw4,
  4362. try_transform_to_nchw32,
  4363. try_transform_to_nchw64, try_transform_to_nchw](
  4364. OperatorNodeBase* opr,
  4365. const VarNodeArray& new_inp) {
  4366. using Param = megdnn::param::ConvBias;
  4367. using Sparse = Param::Sparse;
  4368. mgb_assert(opr->input().size() == new_inp.size());
  4369. auto& conv_bias = opr->cast_final_safe<opr::ConvBiasForward>();
  4370. mgb_assert(conv_bias.param().sparse == Sparse::DENSE,
  4371. "only support dense conv now");
  4372. VarNode* new_var = nullptr;
  4373. if ((new_var = try_transform_to_nchw32(opr, new_inp)) ||
  4374. (new_var = try_transform_to_nchw4(opr, new_inp)) ||
  4375. (new_var = try_transform_to_nchw64(opr, new_inp))||
  4376. (new_var = try_transform_to_nchw(opr, new_inp))) {
  4377. return new_var->owner_opr();
  4378. } else {
  4379. mgb_assert(
  4380. new_inp[0]->dtype().enumv() != DTypeEnum::QuantizedS8 &&
  4381. new_inp[0]->dtype().enumv() !=
  4382. DTypeEnum::QuantizedS4 &&
  4383. new_inp[0]->dtype().enumv() !=
  4384. DTypeEnum::Quantized4Asymm &&
  4385. new_inp[0]->dtype().enumv() != DTypeEnum::Float32,
  4386. "invalid data type(%s)", new_inp[0]->dtype().name());
  4387. bool shape_changed = false;
  4388. for (const auto& i : new_inp) {
  4389. if (format_map.count(i->owner_opr()) > 0) {
  4390. shape_changed = true;
  4391. break;
  4392. }
  4393. }
  4394. mgb_assert(!shape_changed,
  4395. "EnableNCHW64Pass won't change format of output tensor "
  4396. "of non quantized conv bias operator(name:%s)",
  4397. opr->cname());
  4398. return serialization::copy_opr_shallow(*opr, new_inp,
  4399. opr->config());
  4400. }
  4401. };
  4402. replace_func[opr::ConvBiasForward::typeinfo()] = replace_conv_bias_opr;
  4403. replace_func[opr::ConvolutionBackwardData::
  4404. typeinfo()] = [&format_map](OperatorNodeBase* opr,
  4405. const VarNodeArray&
  4406. new_inp) {
  4407. mgb_assert(opr->input().size() == new_inp.size());
  4408. mgb_assert(new_inp.size() == 2,
  4409. "deconv (conv bwd data) operator for inference can "
  4410. "only have 2 input vars(got:%zu)",
  4411. new_inp.size());
  4412. auto& deconv = opr->cast_final_safe<opr::ConvolutionBackwardData>();
  4413. if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8) {
  4414. Format cur;
  4415. auto iter = format_map.find(new_inp[1]->owner_opr());
  4416. if (iter == format_map.end()) {
  4417. cur = Format::NCHW;
  4418. } else {
  4419. cur = iter->second;
  4420. }
  4421. auto inps = new_inp;
  4422. inps[0] = RelayoutPlaceholder::make(
  4423. inps[0],
  4424. RelayoutPlaceholder::LayoutType::NCHW_TO_NCHW4)
  4425. .node();
  4426. switch (cur) {
  4427. case Format::NCHW:
  4428. inps[1] = RelayoutPlaceholder::make(
  4429. inps[1], RelayoutPlaceholder::LayoutType::
  4430. NCHW_TO_NCHW4)
  4431. .node();
  4432. break;
  4433. case Format::NCHW32:
  4434. inps[1] = RelayoutPlaceholder::make(
  4435. inps[1], RelayoutPlaceholder::LayoutType::
  4436. NCHW32_TO_NCHW4)
  4437. .node();
  4438. break;
  4439. case Format::NCHW64:
  4440. inps[1] = RelayoutPlaceholder::make(
  4441. inps[1], RelayoutPlaceholder::LayoutType::
  4442. NCHW64_TO_NCHW4)
  4443. .node();
  4444. break;
  4445. default:
  4446. mgb_assert(cur == Format::NCHW4);
  4447. }
  4448. auto param = deconv.param();
  4449. param.format = Format::NCHW4;
  4450. auto new_deconv = opr::ConvolutionBackwardData::make(
  4451. inps[0], inps[1], param, deconv.execution_policy(),
  4452. deconv.config());
  4453. auto ret = new_deconv.node()->owner_opr();
  4454. format_map.insert(std::make_pair(ret, Format::NCHW4));
  4455. return ret;
  4456. } else {
  4457. bool shape_changed = false;
  4458. for (const auto& i : new_inp) {
  4459. if (format_map.count(i->owner_opr()) > 0) {
  4460. shape_changed = true;
  4461. break;
  4462. }
  4463. }
  4464. mgb_assert(!shape_changed,
  4465. "EnableNCHW64Pass won't change format of output tensor "
  4466. "of non quantized deconv operator(name:%s)",
  4467. opr->cname());
  4468. return serialization::copy_opr_shallow(*opr, new_inp,
  4469. opr->config());
  4470. }
  4471. };
  4472. // replace rule for elemwise like opr
  4473. auto replace_elemwise_like_opr = [&format_map](OperatorNodeBase* opr,
  4474. const VarNodeArray& new_inp) {
  4475. mgb_assert(opr->input().size() == new_inp.size());
  4476. ThinHashMap<Format, size_t> format_size;
  4477. bool same_format = true;
  4478. bool first_touch = false;
  4479. Format format(Format::NCHW);
  4480. for (const auto& i : new_inp) {
  4481. Format cur;
  4482. auto iter = format_map.find(i->owner_opr());
  4483. if (iter == format_map.end()) {
  4484. cur = Format::NCHW;
  4485. } else {
  4486. cur = iter->second;
  4487. }
  4488. auto& size = format_size[cur];
  4489. size += i->shape().total_nr_elems();
  4490. if (!first_touch) {
  4491. first_touch = true;
  4492. format = cur;
  4493. } else {
  4494. if (format != cur)
  4495. same_format = false;
  4496. }
  4497. }
  4498. if (same_format) {
  4499. auto ret = serialization::copy_opr_shallow(*opr, new_inp,
  4500. opr->config());
  4501. if (format != Format::NCHW)
  4502. format_map.insert(std::make_pair(ret, format));
  4503. return ret;
  4504. }
  4505. Format max_format(Format::NCHW);
  4506. size_t max_size = std::numeric_limits<size_t>::min();
  4507. for (const auto& item : format_size) {
  4508. if (item.second > max_size) {
  4509. max_format = item.first;
  4510. max_size = item.second;
  4511. }
  4512. }
  4513. static const ThinHashMap<std::pair<Format, Format>,
  4514. thin_function<VarNode*(VarNode*)>>
  4515. map = {
  4516. #define cb(_fmt1, _fmt2) \
  4517. { \
  4518. std::make_pair(Format::_fmt1, Format::_fmt2), \
  4519. [](VarNode* in) -> VarNode* { \
  4520. return RelayoutPlaceholder::make( \
  4521. in, RelayoutPlaceholder::LayoutType:: \
  4522. _fmt1##_TO_##_fmt2) \
  4523. .node(); \
  4524. } \
  4525. }
  4526. cb(NCHW, NCHW4), cb(NCHW, NCHW32), cb(NCHW, NCHW64),
  4527. cb(NCHW4, NCHW), cb(NCHW4, NCHW32), cb(NCHW4, NCHW64),
  4528. cb(NCHW32, NCHW), cb(NCHW32, NCHW4), cb(NCHW32, NCHW64),
  4529. cb(NCHW32, NCHW), cb(NCHW32, NCHW4), cb(NCHW32, NCHW64),
  4530. #undef cb
  4531. };
  4532. auto inps = new_inp;
  4533. for (size_t i = 0; i < opr->input().size(); ++i) {
  4534. auto iter = format_map.find(new_inp[i]->owner_opr());
  4535. Format cur;
  4536. if (iter != format_map.end()) {
  4537. cur = iter->second;
  4538. } else {
  4539. cur = Format::NCHW;
  4540. }
  4541. if (cur != max_format) {
  4542. inps[i] = map.at(std::make_pair(cur, max_format))(inps[i]);
  4543. }
  4544. }
  4545. auto ret = serialization::copy_opr_shallow(*opr, inps, opr->config());
  4546. if (max_format != Format::NCHW)
  4547. format_map.insert(std::make_pair(ret, max_format));
  4548. return ret;
  4549. };
  4550. // elemwise like
  4551. replace_func[opr::Elemwise::typeinfo()] = replace_elemwise_like_opr;
  4552. replace_func[opr::TypeCvt::typeinfo()] = replace_elemwise_like_opr;
  4553. replace_func[opr::ElemwiseMultiType::typeinfo()] =
  4554. replace_elemwise_like_opr;
  4555. replace_func[opr::PowC::typeinfo()] = replace_elemwise_like_opr;
  4556. auto replace_warp_perspective_opr = [&format_map](
  4557. OperatorNodeBase* opr,
  4558. const VarNodeArray& new_inp) {
  4559. mgb_assert(opr->input().size() == new_inp.size());
  4560. auto& warp = opr->cast_final_safe<opr::WarpPerspectiveForward>();
  4561. if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS4 ||
  4562. new_inp[0]->dtype().enumv() == DTypeEnum::Quantized4Asymm) {
  4563. Format cur;
  4564. auto iter = format_map.find(new_inp[0]->owner_opr());
  4565. if (iter == format_map.end()) {
  4566. cur = Format::NCHW;
  4567. } else {
  4568. cur = iter->second;
  4569. }
  4570. auto inps = new_inp;
  4571. switch (cur) {
  4572. case Format::NCHW:
  4573. inps[0] = RelayoutPlaceholder::make(
  4574. inps[0], RelayoutPlaceholder::LayoutType::
  4575. NCHW_TO_NCHW64)
  4576. .node();
  4577. break;
  4578. case Format::NCHW4:
  4579. inps[0] = RelayoutPlaceholder::make(
  4580. inps[0], RelayoutPlaceholder::LayoutType::
  4581. NCHW4_TO_NCHW64)
  4582. .node();
  4583. break;
  4584. case Format::NCHW32:
  4585. inps[0] = RelayoutPlaceholder::make(
  4586. inps[0], RelayoutPlaceholder::LayoutType::
  4587. NCHW32_TO_NCHW64)
  4588. .node();
  4589. break;
  4590. default:
  4591. mgb_assert(cur == Format::NCHW64);
  4592. }
  4593. auto param = warp.param();
  4594. param.format = Format::NCHW64;
  4595. SymbolVar new_warp;
  4596. if (inps.size() == 3) {
  4597. new_warp = opr::WarpPerspectiveForward::make(
  4598. inps[0], inps[1], inps[2], param,
  4599. warp.config());
  4600. } else {
  4601. mgb_assert(inps.size() == 4);
  4602. new_warp = opr::WarpPerspectiveForward::make(
  4603. inps[0], inps[1], inps[2], inps[3], param,
  4604. warp.config());
  4605. }
  4606. auto ret = new_warp.node()->owner_opr();
  4607. format_map.insert(std::make_pair(ret, Format::NCHW64));
  4608. return ret;
  4609. } else if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8) {
  4610. Format cur;
  4611. auto iter = format_map.find(new_inp[0]->owner_opr());
  4612. if (iter == format_map.end()) {
  4613. cur = Format::NCHW;
  4614. } else {
  4615. cur = iter->second;
  4616. }
  4617. auto inps = new_inp;
  4618. switch (cur) {
  4619. case Format::NCHW:
  4620. inps[0] = RelayoutPlaceholder::make(
  4621. inps[0], RelayoutPlaceholder::LayoutType::
  4622. NCHW_TO_NCHW4)
  4623. .node();
  4624. break;
  4625. case Format::NCHW32:
  4626. inps[0] = RelayoutPlaceholder::make(
  4627. inps[0], RelayoutPlaceholder::LayoutType::
  4628. NCHW32_TO_NCHW4)
  4629. .node();
  4630. break;
  4631. case Format::NCHW64:
  4632. inps[0] = RelayoutPlaceholder::make(
  4633. inps[0], RelayoutPlaceholder::LayoutType::
  4634. NCHW64_TO_NCHW4)
  4635. .node();
  4636. break;
  4637. default:
  4638. mgb_assert(cur == Format::NCHW4);
  4639. }
  4640. auto param = warp.param();
  4641. param.format = Format::NCHW4;
  4642. SymbolVar new_warp;
  4643. if (inps.size() == 3) {
  4644. new_warp = opr::WarpPerspectiveForward::make(
  4645. inps[0], inps[1], inps[2], param,
  4646. warp.config());
  4647. } else {
  4648. mgb_assert(inps.size() == 4);
  4649. new_warp = opr::WarpPerspectiveForward::make(
  4650. inps[0], inps[1], inps[2], inps[3], param,
  4651. warp.config());
  4652. }
  4653. auto ret = new_warp.node()->owner_opr();
  4654. format_map.insert(std::make_pair(ret, Format::NCHW4));
  4655. return ret;
  4656. } else {
  4657. bool shape_changed = false;
  4658. for (const auto& i : new_inp) {
  4659. if (format_map.count(i->owner_opr()) > 0) {
  4660. shape_changed = true;
  4661. break;
  4662. }
  4663. }
  4664. mgb_assert(!shape_changed,
  4665. "EnableNCHW64Pass won't change format of output tensor "
  4666. "of non quantized warp perspective operator(name:%s)",
  4667. opr->cname());
  4668. return serialization::copy_opr_shallow(*opr, new_inp,
  4669. opr->config());
  4670. }
  4671. };
  4672. auto replace_pooling_opr = [&format_map](
  4673. OperatorNodeBase* opr,
  4674. const VarNodeArray& new_inp) {
  4675. mgb_assert(opr->input().size() == new_inp.size());
  4676. auto& pooling = opr->cast_final_safe<opr::PoolingForward>();
  4677. if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS4 ||
  4678. new_inp[0]->dtype().enumv() == DTypeEnum::Quantized4Asymm) {
  4679. Format cur;
  4680. auto iter = format_map.find(new_inp[0]->owner_opr());
  4681. if (iter == format_map.end()) {
  4682. cur = Format::NCHW;
  4683. } else {
  4684. cur = iter->second;
  4685. }
  4686. auto inps = new_inp;
  4687. switch (cur) {
  4688. case Format::NCHW:
  4689. inps[0] = RelayoutPlaceholder::make(
  4690. inps[0], RelayoutPlaceholder::LayoutType::
  4691. NCHW_TO_NCHW64)
  4692. .node();
  4693. break;
  4694. case Format::NCHW4:
  4695. inps[0] = RelayoutPlaceholder::make(
  4696. inps[0], RelayoutPlaceholder::LayoutType::
  4697. NCHW4_TO_NCHW64)
  4698. .node();
  4699. break;
  4700. case Format::NCHW32:
  4701. inps[0] = RelayoutPlaceholder::make(
  4702. inps[0], RelayoutPlaceholder::LayoutType::
  4703. NCHW32_TO_NCHW64)
  4704. .node();
  4705. break;
  4706. default:
  4707. mgb_assert(cur == Format::NCHW64);
  4708. }
  4709. auto param = pooling.param();
  4710. param.format = Format::NCHW64;
  4711. auto new_pool =
  4712. opr::PoolingForward::make(inps[0], param, pooling.config());
  4713. auto ret = new_pool.node()->owner_opr();
  4714. format_map.insert(std::make_pair(ret, Format::NCHW64));
  4715. return ret;
  4716. } else if (new_inp[0]->dtype().enumv() == DTypeEnum::QuantizedS8) {
  4717. Format cur;
  4718. auto iter = format_map.find(new_inp[0]->owner_opr());
  4719. if (iter == format_map.end()) {
  4720. cur = Format::NCHW;
  4721. } else {
  4722. cur = iter->second;
  4723. }
  4724. size_t in_channels = new_inp[0]->shape()[1];
  4725. bool use_nchw32 = false;
  4726. auto inps = new_inp;
  4727. using LayoutType = RelayoutPlaceholder::LayoutType;
  4728. switch (cur) {
  4729. case Format::NCHW: {
  4730. use_nchw32 = in_channels % 32 == 0;
  4731. auto layout_type = use_nchw32 ? LayoutType::NCHW_TO_NCHW32
  4732. : LayoutType::NCHW_TO_NCHW4;
  4733. inps[0] = RelayoutPlaceholder::make(inps[0], layout_type)
  4734. .node();
  4735. break;
  4736. }
  4737. case Format::NCHW64:
  4738. inps[0] = RelayoutPlaceholder::make(
  4739. inps[0], RelayoutPlaceholder::LayoutType::
  4740. NCHW64_TO_NCHW32)
  4741. .node();
  4742. break;
  4743. case Format::NCHW32:
  4744. use_nchw32 = true;
  4745. break;
  4746. default:
  4747. mgb_assert(cur == Format::NCHW4);
  4748. }
  4749. Format out_format = use_nchw32 ? Format::NCHW32 : Format::NCHW4;
  4750. auto param = pooling.param();
  4751. param.format = out_format;
  4752. auto new_pool =
  4753. opr::PoolingForward::make(inps[0], param, pooling.config());
  4754. auto ret = new_pool.node()->owner_opr();
  4755. format_map.insert(std::make_pair(ret, out_format));
  4756. return ret;
  4757. } else {
  4758. bool shape_changed = false;
  4759. for (const auto& i : new_inp) {
  4760. if (format_map.count(i->owner_opr()) > 0) {
  4761. shape_changed = true;
  4762. break;
  4763. }
  4764. }
  4765. mgb_assert(!shape_changed,
  4766. "EnableNCHW64Pass won't change format of output tensor "
  4767. "of non quantized pooling operator(name:%s)",
  4768. opr->cname());
  4769. return serialization::copy_opr_shallow(*opr, new_inp,
  4770. opr->config());
  4771. }
  4772. };
  4773. // format aware
  4774. replace_func[opr::WarpPerspectiveForward::typeinfo()] =
  4775. replace_warp_perspective_opr;
  4776. replace_func[opr::PoolingForward::typeinfo()] = replace_pooling_opr;
  4777. // to nchw
  4778. auto replace_inps_to_nchw = [&format_map](OperatorNodeBase* opr,
  4779. const VarNodeArray& new_inp) {
  4780. mgb_assert(opr->input().size() == new_inp.size());
  4781. auto inps = new_inp;
  4782. for (size_t i = 0; i < opr->input().size(); ++i) {
  4783. auto iter = format_map.find(new_inp[i]->owner_opr());
  4784. auto fmt = iter != format_map.end()?iter->second:Format::NCHW;
  4785. if (iter != format_map.end()) {
  4786. switch (fmt) {
  4787. case Format::NCHW4:
  4788. inps[i] = RelayoutPlaceholder::make(
  4789. inps[i],
  4790. RelayoutPlaceholder::LayoutType::
  4791. NCHW4_TO_NCHW)
  4792. .node();
  4793. break;
  4794. case Format::NCHW32:
  4795. inps[i] = RelayoutPlaceholder::make(
  4796. inps[i],
  4797. RelayoutPlaceholder::LayoutType::
  4798. NCHW32_TO_NCHW)
  4799. .node();
  4800. break;
  4801. default:
  4802. mgb_assert(fmt == Format::NCHW64);
  4803. inps[i] = RelayoutPlaceholder::make(
  4804. inps[i],
  4805. RelayoutPlaceholder::LayoutType::
  4806. NCHW64_TO_NCHW)
  4807. .node();
  4808. break;
  4809. }
  4810. }
  4811. }
  4812. auto ret = serialization::copy_opr_shallow(*opr, inps, opr->config());
  4813. return ret;
  4814. };
  4815. replace_func[opr::Reduce::typeinfo()] = replace_inps_to_nchw;
  4816. replace_func[opr::Concat::typeinfo()] = replace_inps_to_nchw;
  4817. replace_func[opr::Reshape::typeinfo()] = replace_inps_to_nchw;
  4818. replace_func[opr::GetVarShape::typeinfo()] = replace_inps_to_nchw;
  4819. replace_func[opr::Dimshuffle::typeinfo()] = replace_inps_to_nchw;
  4820. replace_func[opr::Subtensor::typeinfo()] = replace_inps_to_nchw;
  4821. return ret;
  4822. MIDOUT_E
  4823. }
  4824. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

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