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.

ncnnoptimize.cpp 130 kB

6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifdef _MSC_VER
  15. #define _CRT_SECURE_NO_DEPRECATE
  16. #endif
  17. #include <algorithm>
  18. #include <map>
  19. #include <set>
  20. #include <vector>
  21. // ncnn public header
  22. #include "datareader.h"
  23. #include "layer.h"
  24. #include "layer_type.h"
  25. #include "net.h"
  26. // ncnn private header
  27. #include "layer/batchnorm.h"
  28. #include "layer/bias.h"
  29. #include "layer/binaryop.h"
  30. #include "layer/clip.h"
  31. #include "layer/concat.h"
  32. #include "layer/convolution.h"
  33. #include "layer/convolutiondepthwise.h"
  34. #include "layer/crop.h"
  35. #include "layer/deconvolution.h"
  36. #include "layer/deconvolutiondepthwise.h"
  37. #include "layer/detectionoutput.h"
  38. #include "layer/dropout.h"
  39. #include "layer/eltwise.h"
  40. #include "layer/elu.h"
  41. #include "layer/exp.h"
  42. #include "layer/expanddims.h"
  43. #include "layer/flatten.h"
  44. #include "layer/gemm.h"
  45. #include "layer/groupnorm.h"
  46. #include "layer/gru.h"
  47. #include "layer/hardsigmoid.h"
  48. #include "layer/hardswish.h"
  49. #include "layer/innerproduct.h"
  50. #include "layer/input.h"
  51. #include "layer/instancenorm.h"
  52. #include "layer/interp.h"
  53. #include "layer/log.h"
  54. #include "layer/lrn.h"
  55. #include "layer/lstm.h"
  56. #include "layer/memorydata.h"
  57. #include "layer/mvn.h"
  58. #include "layer/normalize.h"
  59. #include "layer/padding.h"
  60. #include "layer/permute.h"
  61. #include "layer/pixelshuffle.h"
  62. #include "layer/pooling.h"
  63. #include "layer/power.h"
  64. #include "layer/prelu.h"
  65. #include "layer/priorbox.h"
  66. #include "layer/proposal.h"
  67. #include "layer/psroipooling.h"
  68. #include "layer/quantize.h"
  69. #include "layer/reduction.h"
  70. #include "layer/relu.h"
  71. #include "layer/reorg.h"
  72. #include "layer/requantize.h"
  73. #include "layer/reshape.h"
  74. #include "layer/rnn.h"
  75. #include "layer/roialign.h"
  76. #include "layer/roipooling.h"
  77. #include "layer/scale.h"
  78. #include "layer/shufflechannel.h"
  79. #include "layer/slice.h"
  80. #include "layer/softmax.h"
  81. #include "layer/split.h"
  82. #include "layer/squeeze.h"
  83. #include "layer/threshold.h"
  84. #include "layer/unaryop.h"
  85. #include "layer/yolodetectionoutput.h"
  86. #include "layer/yolov3detectionoutput.h"
  87. class DataReaderFromEmpty : public ncnn::DataReader
  88. {
  89. public:
  90. virtual int scan(const char* format, void* p) const
  91. {
  92. return 0;
  93. }
  94. virtual size_t read(void* /*buf*/, size_t size) const
  95. {
  96. return size;
  97. }
  98. };
  99. class MemoryFootprintAllocator : public ncnn::Allocator
  100. {
  101. public:
  102. MemoryFootprintAllocator()
  103. {
  104. current_memory_usage = 0;
  105. memory_footprint = 0;
  106. }
  107. virtual void* fastMalloc(size_t size)
  108. {
  109. ncnn::MutexLockGuard g(lock);
  110. void* ptr = ncnn::fastMalloc(size);
  111. bookkeeper[ptr] = size;
  112. current_memory_usage += size;
  113. memory_footprint = std::max(memory_footprint, current_memory_usage);
  114. return ptr;
  115. }
  116. virtual void fastFree(void* ptr)
  117. {
  118. ncnn::MutexLockGuard g(lock);
  119. size_t size = bookkeeper[ptr];
  120. current_memory_usage -= size;
  121. bookkeeper.erase(bookkeeper.find(ptr));
  122. ncnn::fastFree(ptr);
  123. }
  124. public:
  125. int current_memory_usage;
  126. int memory_footprint;
  127. ncnn::Mutex lock;
  128. std::map<void*, size_t> bookkeeper;
  129. };
  130. class CustomLayer : public ncnn::Layer
  131. {
  132. public:
  133. virtual int load_param(const ncnn::ParamDict& pd)
  134. {
  135. mpd = pd;
  136. return 0;
  137. }
  138. void write_param(FILE* pp)
  139. {
  140. for (int i = 0; i < NCNN_MAX_PARAM_COUNT; i++)
  141. {
  142. int type = mpd.type(i);
  143. if (type == 0)
  144. continue;
  145. if (type == 2)
  146. {
  147. fprintf(pp, " %d=%d", i, mpd.get(i, 0));
  148. }
  149. if (type == 3)
  150. {
  151. fprintf(pp, " %d=%e", i, mpd.get(i, 0.f));
  152. }
  153. if (type == 5)
  154. {
  155. ncnn::Mat v = mpd.get(i, ncnn::Mat());
  156. int len = v.w;
  157. fprintf(pp, " %d=%d", -i - 23300, len);
  158. const int* p = v;
  159. for (int j = 0; j < len; j++)
  160. {
  161. fprintf(pp, ",%d", p[j]);
  162. }
  163. }
  164. if (type == 6)
  165. {
  166. ncnn::Mat v = mpd.get(i, ncnn::Mat());
  167. int len = v.w;
  168. fprintf(pp, " %d=%d", -i - 23300, len);
  169. const float* p = v;
  170. for (int j = 0; j < len; j++)
  171. {
  172. fprintf(pp, ",%e", p[j]);
  173. }
  174. }
  175. }
  176. }
  177. public:
  178. ncnn::ParamDict mpd;
  179. };
  180. DEFINE_LAYER_CREATOR(CustomLayer)
  181. class NetOptimize : public ncnn::Net
  182. {
  183. public:
  184. NetOptimize();
  185. std::vector<ncnn::Blob>& blobs;
  186. std::vector<ncnn::Layer*>& layers;
  187. virtual ncnn::Layer* create_custom_layer(const char* type);
  188. bool has_custom_layer;
  189. public:
  190. // 0=fp32 1=fp16
  191. int storage_type;
  192. // Cut param and bin -1=no cut
  193. int cutstart;
  194. int cutend;
  195. public:
  196. int fuse_batchnorm_scale();
  197. int fuse_convolution_batchnorm();
  198. int fuse_convolution_mul();
  199. int fuse_convolution_add();
  200. int fuse_convolutiondepthwise_batchnorm();
  201. int fuse_convolutiondepthwise_mul();
  202. int fuse_convolutiondepthwise_add();
  203. int fuse_deconvolution_batchnorm();
  204. int fuse_deconvolution_mul();
  205. int fuse_deconvolution_add();
  206. int fuse_deconvolutiondepthwise_batchnorm();
  207. int fuse_innerproduct_batchnorm();
  208. int fuse_innerproduct_add();
  209. int fuse_innerproduct_dropout();
  210. int fuse_convolution_activation();
  211. int fuse_convolutiondepthwise_activation();
  212. int fuse_deconvolution_activation();
  213. int fuse_deconvolutiondepthwise_activation();
  214. int fuse_innerproduct_activation();
  215. int fuse_memorydata_binaryop();
  216. int fuse_binaryop_eltwise();
  217. int eliminate_dropout();
  218. int eliminate_pooling1x1();
  219. int eliminate_noop();
  220. int eliminate_orphaned_memorydata();
  221. int eliminate_flatten_after_global_pooling();
  222. int eliminate_reshape_after_global_pooling();
  223. int eliminate_flatten_after_innerproduct();
  224. int eliminate_reshape_before_binaryop();
  225. int replace_reduction_with_global_pooling();
  226. int replace_prelu_with_leaky_relu();
  227. int replace_convolution_with_innerproduct_after_global_pooling();
  228. int replace_convolution_with_innerproduct_after_innerproduct();
  229. int shape_inference();
  230. int estimate_memory_footprint();
  231. int set_cutparam(const char* cutstartname, const char* cutendname);
  232. public:
  233. int fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp);
  234. int fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp);
  235. int fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp);
  236. int fwrite_weight_data(const ncnn::Mat& data, FILE* bp);
  237. int save(const char* parampath, const char* binpath);
  238. };
  239. NetOptimize::NetOptimize()
  240. : blobs(mutable_blobs()), layers(mutable_layers())
  241. {
  242. has_custom_layer = false;
  243. cutstart = -1;
  244. cutend = -1;
  245. }
  246. ncnn::Layer* NetOptimize::create_custom_layer(const char* type)
  247. {
  248. ncnn::Layer* layer = Net::create_custom_layer(type);
  249. if (layer)
  250. return layer;
  251. fprintf(stderr, "create_custom_layer %s\n", type);
  252. register_custom_layer(type, CustomLayer_layer_creator);
  253. has_custom_layer = true;
  254. return Net::create_custom_layer(type);
  255. }
  256. int NetOptimize::fuse_batchnorm_scale()
  257. {
  258. const size_t layer_count = layers.size();
  259. for (size_t i = 0; i < layer_count; i++)
  260. {
  261. if (layers[i]->type != "BatchNorm")
  262. continue;
  263. // BatchNorm - Scale
  264. int top_blob_index = layers[i]->tops[0];
  265. size_t j = i + 1;
  266. for (; j < layer_count; j++)
  267. {
  268. if (layers[j]->type != "Scale")
  269. continue;
  270. if (layers[j]->bottoms.size() != 1)
  271. continue;
  272. if (layers[j]->bottoms[0] == top_blob_index)
  273. break;
  274. }
  275. if (j == layer_count)
  276. continue;
  277. // fuse BatchNorm - Scale to BatchNorm
  278. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[i];
  279. ncnn::Scale* scale = (ncnn::Scale*)layers[j];
  280. fprintf(stderr, "fuse_batchnorm_scale %s %s\n", batchnorm->name.c_str(), scale->name.c_str());
  281. {
  282. // v = ((v - mean) / sqrt(var + eps) * slope + bias) * s + b
  283. // = (v - mean) / sqrt(var + eps) * (slope * s) + (bias * s + b)
  284. int channels = batchnorm->channels;
  285. float* slope = batchnorm->slope_data;
  286. float* bias = batchnorm->bias_data;
  287. for (int q = 0; q < channels; q++)
  288. {
  289. slope[q] = slope[q] * scale->scale_data[q];
  290. if (scale->bias_term)
  291. bias[q] = bias[q] * scale->scale_data[q] + scale->bias_data[q];
  292. else
  293. bias[q] = bias[q] * scale->scale_data[q];
  294. }
  295. }
  296. int top_blob_index_final = scale->tops[0];
  297. batchnorm->tops[0] = top_blob_index_final;
  298. blobs[top_blob_index_final].producer = i;
  299. scale->type = "ncnnfused";
  300. }
  301. return 0;
  302. }
  303. int NetOptimize::fuse_convolution_batchnorm()
  304. {
  305. const size_t layer_count = layers.size();
  306. for (size_t i = 0; i < layer_count; i++)
  307. {
  308. if (layers[i]->type != "Convolution")
  309. continue;
  310. // Convolution - BatchNorm
  311. int top_blob_index = layers[i]->tops[0];
  312. size_t j = i + 1;
  313. for (; j < layer_count; j++)
  314. {
  315. if (layers[j]->type != "BatchNorm")
  316. continue;
  317. if (layers[j]->bottoms.size() != 1)
  318. continue;
  319. if (layers[j]->bottoms[0] == top_blob_index)
  320. break;
  321. }
  322. if (j == layer_count)
  323. continue;
  324. // fuse Convolution - BatchNorm to Convolution
  325. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  326. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  327. fprintf(stderr, "fuse_convolution_batchnorm %s %s\n", convolution->name.c_str(), batchnorm->name.c_str());
  328. {
  329. int channels = batchnorm->channels;
  330. float eps = batchnorm->eps;
  331. // a = bias - slope * mean / sqrt(var + eps)
  332. // b = slope / sqrt(var + eps)
  333. // value = value * b + a
  334. std::vector<float> a(channels);
  335. std::vector<float> b(channels);
  336. for (int i = 0; i < channels; i++)
  337. {
  338. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  339. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  340. b[i] = batchnorm->slope_data[i] / sqrt_var;
  341. }
  342. if (convolution->bias_term == 0)
  343. {
  344. // init bias as zero
  345. convolution->bias_term = 1;
  346. convolution->bias_data = ncnn::Mat(channels);
  347. convolution->bias_data.fill(0.f);
  348. }
  349. const int weight_per_outch = convolution->weight_data_size / channels;
  350. float* weight = convolution->weight_data;
  351. float* bias = convolution->bias_data;
  352. for (int i = 0; i < channels; i++)
  353. {
  354. float* conv_weight_outch = weight + weight_per_outch * i;
  355. for (int j = 0; j < weight_per_outch; j++)
  356. {
  357. conv_weight_outch[j] *= b[i];
  358. }
  359. bias[i] = bias[i] * b[i] + a[i];
  360. }
  361. }
  362. int top_blob_index_final = batchnorm->tops[0];
  363. convolution->tops[0] = top_blob_index_final;
  364. blobs[top_blob_index_final].producer = i;
  365. batchnorm->type = "ncnnfused";
  366. }
  367. return 0;
  368. }
  369. int NetOptimize::fuse_convolution_mul()
  370. {
  371. const size_t layer_count = layers.size();
  372. for (size_t i = 0; i < layer_count; i++)
  373. {
  374. if (layers[i]->type != "Convolution")
  375. continue;
  376. // Convolution - BinaryOp
  377. int top_blob_index = layers[i]->tops[0];
  378. size_t j = i + 1;
  379. for (; j < layer_count; j++)
  380. {
  381. if (layers[j]->type != "BinaryOp")
  382. continue;
  383. if (layers[j]->bottoms.size() != 2)
  384. continue;
  385. if (layers[j]->bottoms[0] == top_blob_index)
  386. break;
  387. }
  388. if (j == layer_count)
  389. continue;
  390. // fuse Convolution - BinaryOp to Convolution
  391. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  392. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  393. if (binaryop->op_type != 2 || binaryop->with_scalar)
  394. continue;
  395. // MemoryData - ..... - BinaryOp
  396. size_t k = 0;
  397. for (; k < j; k++)
  398. {
  399. if (layers[k]->type != "MemoryData")
  400. continue;
  401. if (layers[k]->tops[0] == binaryop->bottoms[1])
  402. break;
  403. }
  404. if (k == j)
  405. continue;
  406. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  407. int channels = convolution->num_output;
  408. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  409. {
  410. // not bias-like broadcasting type
  411. continue;
  412. }
  413. fprintf(stderr, "fuse_convolution_mul %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
  414. {
  415. const int weight_per_outch = convolution->weight_data_size / channels;
  416. float* weight = convolution->weight_data;
  417. float* bias = convolution->bias_data;
  418. for (int i = 0; i < channels; i++)
  419. {
  420. float* conv_weight_outch = weight + weight_per_outch * i;
  421. for (int j = 0; j < weight_per_outch; j++)
  422. {
  423. conv_weight_outch[j] *= memorydata->data[i];
  424. }
  425. if (bias)
  426. {
  427. bias[i] = bias[i] * memorydata->data[i];
  428. }
  429. }
  430. }
  431. int top_blob_index_final = binaryop->tops[0];
  432. convolution->tops[0] = top_blob_index_final;
  433. blobs[top_blob_index_final].producer = i;
  434. binaryop->type = "ncnnfused";
  435. }
  436. return 0;
  437. }
  438. int NetOptimize::fuse_convolution_add()
  439. {
  440. const size_t layer_count = layers.size();
  441. for (size_t i = 0; i < layer_count; i++)
  442. {
  443. if (layers[i]->type != "Convolution")
  444. continue;
  445. // Convolution - BinaryOp
  446. int top_blob_index = layers[i]->tops[0];
  447. size_t j = i + 1;
  448. for (; j < layer_count; j++)
  449. {
  450. if (layers[j]->type != "BinaryOp")
  451. continue;
  452. if (layers[j]->bottoms.size() != 2)
  453. continue;
  454. if (layers[j]->bottoms[0] == top_blob_index)
  455. break;
  456. }
  457. if (j == layer_count)
  458. continue;
  459. // fuse Convolution - BinaryOp to Convolution
  460. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  461. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  462. if (binaryop->op_type != 0 || binaryop->with_scalar)
  463. continue;
  464. // MemoryData - ..... - BinaryOp
  465. size_t k = 0;
  466. for (; k < j; k++)
  467. {
  468. if (layers[k]->type != "MemoryData")
  469. continue;
  470. if (layers[k]->tops[0] == binaryop->bottoms[1])
  471. break;
  472. }
  473. if (k == j)
  474. continue;
  475. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  476. int channels = convolution->num_output;
  477. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  478. {
  479. // not bias-like broadcasting type
  480. continue;
  481. }
  482. fprintf(stderr, "fuse_convolution_add %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
  483. {
  484. if (convolution->bias_term == 0)
  485. {
  486. // init bias
  487. convolution->bias_term = 1;
  488. convolution->bias_data = memorydata->data;
  489. }
  490. else
  491. {
  492. float* bias = convolution->bias_data;
  493. for (int i = 0; i < channels; i++)
  494. {
  495. bias[i] = bias[i] + memorydata->data[i];
  496. }
  497. }
  498. }
  499. int top_blob_index_final = binaryop->tops[0];
  500. convolution->tops[0] = top_blob_index_final;
  501. blobs[top_blob_index_final].producer = i;
  502. binaryop->type = "ncnnfused";
  503. }
  504. return 0;
  505. }
  506. int NetOptimize::fuse_convolutiondepthwise_batchnorm()
  507. {
  508. const size_t layer_count = layers.size();
  509. for (size_t i = 0; i < layer_count; i++)
  510. {
  511. if (layers[i]->type != "ConvolutionDepthWise")
  512. continue;
  513. // ConvolutionDepthWise - BatchNorm
  514. int top_blob_index = layers[i]->tops[0];
  515. size_t j = i + 1;
  516. for (; j < layer_count; j++)
  517. {
  518. if (layers[j]->type != "BatchNorm")
  519. continue;
  520. if (layers[j]->bottoms.size() != 1)
  521. continue;
  522. if (layers[j]->bottoms[0] == top_blob_index)
  523. break;
  524. }
  525. if (j == layer_count)
  526. continue;
  527. // fuse ConvolutionDepthWise - BatchNorm to ConvolutionDepthWise
  528. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  529. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  530. fprintf(stderr, "fuse_convolutiondepthwise_batchnorm %s %s\n", convolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  531. {
  532. int channels = batchnorm->channels;
  533. float eps = batchnorm->eps;
  534. // a = bias - slope * mean / sqrt(var + eps)
  535. // b = slope / sqrt(var + eps)
  536. // value = value * b + a
  537. std::vector<float> a(channels);
  538. std::vector<float> b(channels);
  539. for (int i = 0; i < channels; i++)
  540. {
  541. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  542. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  543. b[i] = batchnorm->slope_data[i] / sqrt_var;
  544. }
  545. if (convolutiondepthwise->bias_term == 0)
  546. {
  547. // init bias as zero
  548. convolutiondepthwise->bias_term = 1;
  549. convolutiondepthwise->bias_data = ncnn::Mat(channels);
  550. convolutiondepthwise->bias_data.fill(0.f);
  551. }
  552. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  553. float* weight = convolutiondepthwise->weight_data;
  554. float* bias = convolutiondepthwise->bias_data;
  555. for (int i = 0; i < channels; i++)
  556. {
  557. float* conv_weight_outch = weight + weight_per_outch * i;
  558. for (int j = 0; j < weight_per_outch; j++)
  559. {
  560. conv_weight_outch[j] *= b[i];
  561. }
  562. bias[i] = bias[i] * b[i] + a[i];
  563. }
  564. }
  565. int top_blob_index_final = batchnorm->tops[0];
  566. convolutiondepthwise->tops[0] = top_blob_index_final;
  567. blobs[top_blob_index_final].producer = i;
  568. batchnorm->type = "ncnnfused";
  569. }
  570. return 0;
  571. }
  572. int NetOptimize::fuse_convolutiondepthwise_mul()
  573. {
  574. const size_t layer_count = layers.size();
  575. for (size_t i = 0; i < layer_count; i++)
  576. {
  577. if (layers[i]->type != "ConvolutionDepthWise")
  578. continue;
  579. // ConvolutionDepthWise - BinaryOp
  580. int top_blob_index = layers[i]->tops[0];
  581. size_t j = i + 1;
  582. for (; j < layer_count; j++)
  583. {
  584. if (layers[j]->type != "BinaryOp")
  585. continue;
  586. if (layers[j]->bottoms.size() != 2)
  587. continue;
  588. if (layers[j]->bottoms[0] == top_blob_index)
  589. break;
  590. }
  591. if (j == layer_count)
  592. continue;
  593. // fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
  594. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  595. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  596. if (binaryop->op_type != 2 || binaryop->with_scalar)
  597. continue;
  598. // MemoryData - ..... - BinaryOp
  599. size_t k = 0;
  600. for (; k < j; k++)
  601. {
  602. if (layers[k]->type != "MemoryData")
  603. continue;
  604. if (layers[k]->tops[0] == binaryop->bottoms[1])
  605. break;
  606. }
  607. if (k == j)
  608. continue;
  609. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  610. int channels = convolutiondepthwise->num_output;
  611. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  612. {
  613. // not bias-like broadcasting type
  614. continue;
  615. }
  616. fprintf(stderr, "fuse_convolutiondepthwise_mul %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
  617. {
  618. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  619. float* weight = convolutiondepthwise->weight_data;
  620. float* bias = convolutiondepthwise->bias_data;
  621. for (int i = 0; i < channels; i++)
  622. {
  623. float* conv_weight_outch = weight + weight_per_outch * i;
  624. for (int j = 0; j < weight_per_outch; j++)
  625. {
  626. conv_weight_outch[j] *= memorydata->data[i];
  627. }
  628. if (bias)
  629. {
  630. bias[i] = bias[i] * memorydata->data[i];
  631. }
  632. }
  633. }
  634. int top_blob_index_final = binaryop->tops[0];
  635. convolutiondepthwise->tops[0] = top_blob_index_final;
  636. blobs[top_blob_index_final].producer = i;
  637. binaryop->type = "ncnnfused";
  638. }
  639. return 0;
  640. }
  641. int NetOptimize::fuse_convolutiondepthwise_add()
  642. {
  643. const size_t layer_count = layers.size();
  644. for (size_t i = 0; i < layer_count; i++)
  645. {
  646. if (layers[i]->type != "ConvolutionDepthWise")
  647. continue;
  648. // ConvolutionDepthWise - BinaryOp
  649. int top_blob_index = layers[i]->tops[0];
  650. size_t j = i + 1;
  651. for (; j < layer_count; j++)
  652. {
  653. if (layers[j]->type != "BinaryOp")
  654. continue;
  655. if (layers[j]->bottoms.size() != 2)
  656. continue;
  657. if (layers[j]->bottoms[0] == top_blob_index)
  658. break;
  659. }
  660. if (j == layer_count)
  661. continue;
  662. // fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
  663. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  664. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  665. if (binaryop->op_type != 0 || binaryop->with_scalar)
  666. continue;
  667. // MemoryData - ..... - BinaryOp
  668. size_t k = 0;
  669. for (; k < j; k++)
  670. {
  671. if (layers[k]->type != "MemoryData")
  672. continue;
  673. if (layers[k]->tops[0] == binaryop->bottoms[1])
  674. break;
  675. }
  676. if (k == j)
  677. continue;
  678. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  679. int channels = convolutiondepthwise->num_output;
  680. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  681. {
  682. // not bias-like broadcasting type
  683. continue;
  684. }
  685. fprintf(stderr, "fuse_convolutiondepthwise_add %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
  686. {
  687. if (convolutiondepthwise->bias_term == 0)
  688. {
  689. // init bias
  690. convolutiondepthwise->bias_term = 1;
  691. convolutiondepthwise->bias_data = memorydata->data;
  692. }
  693. else
  694. {
  695. float* bias = convolutiondepthwise->bias_data;
  696. for (int i = 0; i < channels; i++)
  697. {
  698. bias[i] = bias[i] + memorydata->data[i];
  699. }
  700. }
  701. }
  702. int top_blob_index_final = binaryop->tops[0];
  703. convolutiondepthwise->tops[0] = top_blob_index_final;
  704. blobs[top_blob_index_final].producer = i;
  705. binaryop->type = "ncnnfused";
  706. }
  707. return 0;
  708. }
  709. int NetOptimize::fuse_deconvolution_batchnorm()
  710. {
  711. const size_t layer_count = layers.size();
  712. for (size_t i = 0; i < layer_count; i++)
  713. {
  714. if (layers[i]->type != "Deconvolution")
  715. continue;
  716. // Deconvolution - BatchNorm
  717. int top_blob_index = layers[i]->tops[0];
  718. size_t j = i + 1;
  719. for (; j < layer_count; j++)
  720. {
  721. if (layers[j]->type != "BatchNorm")
  722. continue;
  723. if (layers[j]->bottoms.size() != 1)
  724. continue;
  725. if (layers[j]->bottoms[0] == top_blob_index)
  726. break;
  727. }
  728. if (j == layer_count)
  729. continue;
  730. // fuse Deconvolution - BatchNorm to Deconvolution
  731. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  732. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  733. fprintf(stderr, "fuse_deconvolution_batchnorm %s %s\n", deconvolution->name.c_str(), batchnorm->name.c_str());
  734. {
  735. int channels = batchnorm->channels;
  736. float eps = batchnorm->eps;
  737. // a = bias - slope * mean / sqrt(var + eps)
  738. // b = slope / sqrt(var + eps)
  739. // value = value * b + a
  740. std::vector<float> a(channels);
  741. std::vector<float> b(channels);
  742. for (int i = 0; i < channels; i++)
  743. {
  744. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  745. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  746. b[i] = batchnorm->slope_data[i] / sqrt_var;
  747. }
  748. if (deconvolution->bias_term == 0)
  749. {
  750. // init bias as zero
  751. deconvolution->bias_term = 1;
  752. deconvolution->bias_data = ncnn::Mat(channels);
  753. deconvolution->bias_data.fill(0.f);
  754. }
  755. const int weight_per_outch = deconvolution->weight_data_size / channels;
  756. float* weight = deconvolution->weight_data;
  757. float* bias = deconvolution->bias_data;
  758. for (int i = 0; i < channels; i++)
  759. {
  760. float* conv_weight_outch = weight + weight_per_outch * i;
  761. for (int j = 0; j < weight_per_outch; j++)
  762. {
  763. conv_weight_outch[j] *= b[i];
  764. }
  765. bias[i] = bias[i] * b[i] + a[i];
  766. }
  767. }
  768. int top_blob_index_final = batchnorm->tops[0];
  769. deconvolution->tops[0] = top_blob_index_final;
  770. blobs[top_blob_index_final].producer = i;
  771. batchnorm->type = "ncnnfused";
  772. }
  773. return 0;
  774. }
  775. int NetOptimize::fuse_deconvolution_mul()
  776. {
  777. const size_t layer_count = layers.size();
  778. for (size_t i = 0; i < layer_count; i++)
  779. {
  780. if (layers[i]->type != "Deconvolution")
  781. continue;
  782. // Deconvolution - BinaryOp
  783. int top_blob_index = layers[i]->tops[0];
  784. size_t j = i + 1;
  785. for (; j < layer_count; j++)
  786. {
  787. if (layers[j]->type != "BinaryOp")
  788. continue;
  789. if (layers[j]->bottoms.size() != 2)
  790. continue;
  791. if (layers[j]->bottoms[0] == top_blob_index)
  792. break;
  793. }
  794. if (j == layer_count)
  795. continue;
  796. // fuse Deconvolution - BinaryOp to Deconvolution
  797. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  798. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  799. if (binaryop->op_type != 2 || binaryop->with_scalar)
  800. continue;
  801. // MemoryData - ..... - BinaryOp
  802. size_t k = 0;
  803. for (; k < j; k++)
  804. {
  805. if (layers[k]->type != "MemoryData")
  806. continue;
  807. if (layers[k]->tops[0] == binaryop->bottoms[1])
  808. break;
  809. }
  810. if (k == j)
  811. continue;
  812. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  813. int channels = deconvolution->num_output;
  814. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  815. {
  816. // not bias-like broadcasting type
  817. continue;
  818. }
  819. fprintf(stderr, "fuse_deconvolution_mul %s %s\n", deconvolution->name.c_str(), binaryop->name.c_str());
  820. {
  821. const int weight_per_outch = deconvolution->weight_data_size / channels;
  822. float* weight = deconvolution->weight_data;
  823. float* bias = deconvolution->bias_data;
  824. for (int i = 0; i < channels; i++)
  825. {
  826. float* conv_weight_outch = weight + weight_per_outch * i;
  827. for (int j = 0; j < weight_per_outch; j++)
  828. {
  829. conv_weight_outch[j] *= memorydata->data[i];
  830. }
  831. if (bias)
  832. {
  833. bias[i] = bias[i] * memorydata->data[i];
  834. }
  835. }
  836. }
  837. int top_blob_index_final = binaryop->tops[0];
  838. deconvolution->tops[0] = top_blob_index_final;
  839. blobs[top_blob_index_final].producer = i;
  840. binaryop->type = "ncnnfused";
  841. }
  842. return 0;
  843. }
  844. int NetOptimize::fuse_deconvolution_add()
  845. {
  846. const size_t layer_count = layers.size();
  847. for (size_t i = 0; i < layer_count; i++)
  848. {
  849. if (layers[i]->type != "Deconvolution")
  850. continue;
  851. // Deconvolution - BinaryOp
  852. int top_blob_index = layers[i]->tops[0];
  853. size_t j = i + 1;
  854. for (; j < layer_count; j++)
  855. {
  856. if (layers[j]->type != "BinaryOp")
  857. continue;
  858. if (layers[j]->bottoms.size() != 2)
  859. continue;
  860. if (layers[j]->bottoms[0] == top_blob_index)
  861. break;
  862. }
  863. if (j == layer_count)
  864. continue;
  865. // fuse Deconvolution - BinaryOp to Deconvolution
  866. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  867. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  868. if (binaryop->op_type != 0 || binaryop->with_scalar)
  869. continue;
  870. // MemoryData - ..... - BinaryOp
  871. size_t k = 0;
  872. for (; k < j; k++)
  873. {
  874. if (layers[k]->type != "MemoryData")
  875. continue;
  876. if (layers[k]->tops[0] == binaryop->bottoms[1])
  877. break;
  878. }
  879. if (k == j)
  880. continue;
  881. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  882. int channels = deconvolution->num_output;
  883. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  884. {
  885. // not bias-like broadcasting type
  886. continue;
  887. }
  888. fprintf(stderr, "fuse_deconvolution_add %s %s\n", deconvolution->name.c_str(), binaryop->name.c_str());
  889. {
  890. if (deconvolution->bias_term == 0)
  891. {
  892. // init bias
  893. deconvolution->bias_term = 1;
  894. deconvolution->bias_data = memorydata->data;
  895. }
  896. else
  897. {
  898. float* bias = deconvolution->bias_data;
  899. for (int i = 0; i < channels; i++)
  900. {
  901. bias[i] = bias[i] + memorydata->data[i];
  902. }
  903. }
  904. }
  905. int top_blob_index_final = binaryop->tops[0];
  906. deconvolution->tops[0] = top_blob_index_final;
  907. blobs[top_blob_index_final].producer = i;
  908. binaryop->type = "ncnnfused";
  909. }
  910. return 0;
  911. }
  912. int NetOptimize::fuse_deconvolutiondepthwise_batchnorm()
  913. {
  914. const size_t layer_count = layers.size();
  915. for (size_t i = 0; i < layer_count; i++)
  916. {
  917. if (layers[i]->type != "DeconvolutionDepthWise")
  918. continue;
  919. // DeconvolutionDepthWise - BatchNorm
  920. int top_blob_index = layers[i]->tops[0];
  921. size_t j = i + 1;
  922. for (; j < layer_count; j++)
  923. {
  924. if (layers[j]->type != "BatchNorm")
  925. continue;
  926. if (layers[j]->bottoms.size() != 1)
  927. continue;
  928. if (layers[j]->bottoms[0] == top_blob_index)
  929. break;
  930. }
  931. if (j == layer_count)
  932. continue;
  933. // fuse DeconvolutionDepthWise - BatchNorm to DeconvolutionDepthWise
  934. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  935. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  936. fprintf(stderr, "fuse_deconvolutiondepthwise_batchnorm %s %s\n", deconvolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  937. {
  938. int channels = batchnorm->channels;
  939. float eps = batchnorm->eps;
  940. // a = bias - slope * mean / sqrt(var + eps)
  941. // b = slope / sqrt(var + eps)
  942. // value = value * b + a
  943. std::vector<float> a(channels);
  944. std::vector<float> b(channels);
  945. for (int i = 0; i < channels; i++)
  946. {
  947. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  948. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  949. b[i] = batchnorm->slope_data[i] / sqrt_var;
  950. }
  951. if (deconvolutiondepthwise->bias_term == 0)
  952. {
  953. // init bias as zero
  954. deconvolutiondepthwise->bias_term = 1;
  955. deconvolutiondepthwise->bias_data = ncnn::Mat(channels);
  956. deconvolutiondepthwise->bias_data.fill(0.f);
  957. }
  958. const int weight_per_outch = deconvolutiondepthwise->weight_data_size / channels;
  959. float* weight = deconvolutiondepthwise->weight_data;
  960. float* bias = deconvolutiondepthwise->bias_data;
  961. for (int i = 0; i < channels; i++)
  962. {
  963. float* conv_weight_outch = weight + weight_per_outch * i;
  964. for (int j = 0; j < weight_per_outch; j++)
  965. {
  966. conv_weight_outch[j] *= b[i];
  967. }
  968. bias[i] = bias[i] * b[i] + a[i];
  969. }
  970. }
  971. int top_blob_index_final = batchnorm->tops[0];
  972. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  973. blobs[top_blob_index_final].producer = i;
  974. batchnorm->type = "ncnnfused";
  975. }
  976. return 0;
  977. }
  978. int NetOptimize::fuse_innerproduct_batchnorm()
  979. {
  980. const size_t layer_count = layers.size();
  981. for (size_t i = 0; i < layer_count; i++)
  982. {
  983. if (layers[i]->type != "InnerProduct")
  984. continue;
  985. // InnerProduct - BatchNorm
  986. int top_blob_index = layers[i]->tops[0];
  987. size_t j = i + 1;
  988. for (; j < layer_count; j++)
  989. {
  990. if (layers[j]->type != "BatchNorm")
  991. continue;
  992. if (layers[j]->bottoms.size() != 1)
  993. continue;
  994. if (layers[j]->bottoms[0] == top_blob_index)
  995. break;
  996. }
  997. if (j == layer_count)
  998. continue;
  999. // fuse InnerProduct - BatchNorm to InnerProduct
  1000. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1001. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  1002. fprintf(stderr, "fuse_innerproduct_batchnorm %s %s\n", innerproduct->name.c_str(), batchnorm->name.c_str());
  1003. {
  1004. int channels = batchnorm->channels;
  1005. float eps = batchnorm->eps;
  1006. // a = bias - slope * mean / sqrt(var + eps)
  1007. // b = slope / sqrt(var + eps)
  1008. // value = value * b + a
  1009. std::vector<float> a(channels);
  1010. std::vector<float> b(channels);
  1011. for (int i = 0; i < channels; i++)
  1012. {
  1013. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  1014. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  1015. b[i] = batchnorm->slope_data[i] / sqrt_var;
  1016. }
  1017. if (innerproduct->bias_term == 0)
  1018. {
  1019. // init bias as zero
  1020. innerproduct->bias_term = 1;
  1021. innerproduct->bias_data = ncnn::Mat(channels);
  1022. innerproduct->bias_data.fill(0.f);
  1023. }
  1024. const int weight_per_outch = innerproduct->weight_data_size / channels;
  1025. float* weight = innerproduct->weight_data;
  1026. float* bias = innerproduct->bias_data;
  1027. for (int i = 0; i < channels; i++)
  1028. {
  1029. float* conv_weight_outch = weight + weight_per_outch * i;
  1030. for (int j = 0; j < weight_per_outch; j++)
  1031. {
  1032. conv_weight_outch[j] *= b[i];
  1033. }
  1034. bias[i] = bias[i] * b[i] + a[i];
  1035. }
  1036. }
  1037. int top_blob_index_final = batchnorm->tops[0];
  1038. innerproduct->tops[0] = top_blob_index_final;
  1039. blobs[top_blob_index_final].producer = i;
  1040. batchnorm->type = "ncnnfused";
  1041. }
  1042. return 0;
  1043. }
  1044. int NetOptimize::fuse_innerproduct_add()
  1045. {
  1046. const size_t layer_count = layers.size();
  1047. for (size_t i = 0; i < layer_count; i++)
  1048. {
  1049. if (layers[i]->type != "InnerProduct")
  1050. continue;
  1051. // InnerProduct - BinaryOp
  1052. int top_blob_index = layers[i]->tops[0];
  1053. size_t j = i + 1;
  1054. for (; j < layer_count; j++)
  1055. {
  1056. if (layers[j]->type != "BinaryOp")
  1057. continue;
  1058. if (layers[j]->bottoms.size() != 2)
  1059. continue;
  1060. if (layers[j]->bottoms[0] == top_blob_index)
  1061. break;
  1062. }
  1063. if (j == layer_count)
  1064. continue;
  1065. // fuse InnerProduct - BinaryOp to InnerProduct
  1066. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1067. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1068. if (binaryop->op_type != 0 || binaryop->with_scalar)
  1069. continue;
  1070. // MemoryData - ..... - BinaryOp
  1071. size_t k = 0;
  1072. for (; k < j; k++)
  1073. {
  1074. if (layers[k]->type != "MemoryData")
  1075. continue;
  1076. if (layers[k]->tops[0] == binaryop->bottoms[1])
  1077. break;
  1078. }
  1079. if (k == j)
  1080. continue;
  1081. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  1082. int channels = innerproduct->num_output;
  1083. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  1084. {
  1085. // not bias-like broadcasting type
  1086. continue;
  1087. }
  1088. fprintf(stderr, "fuse_innerproduct_add %s %s\n", innerproduct->name.c_str(), binaryop->name.c_str());
  1089. {
  1090. if (innerproduct->bias_term == 0)
  1091. {
  1092. // init bias
  1093. innerproduct->bias_term = 1;
  1094. innerproduct->bias_data = memorydata->data;
  1095. }
  1096. else
  1097. {
  1098. float* bias = innerproduct->bias_data;
  1099. for (int i = 0; i < channels; i++)
  1100. {
  1101. bias[i] = bias[i] + memorydata->data[i];
  1102. }
  1103. }
  1104. }
  1105. int top_blob_index_final = binaryop->tops[0];
  1106. innerproduct->tops[0] = top_blob_index_final;
  1107. blobs[top_blob_index_final].producer = i;
  1108. binaryop->type = "ncnnfused";
  1109. }
  1110. return 0;
  1111. }
  1112. int NetOptimize::fuse_innerproduct_dropout()
  1113. {
  1114. const size_t layer_count = layers.size();
  1115. for (size_t i = 0; i < layer_count; i++)
  1116. {
  1117. if (layers[i]->type != "InnerProduct")
  1118. continue;
  1119. // InnerProduct - Dropout
  1120. int top_blob_index = layers[i]->tops[0];
  1121. size_t j = i + 1;
  1122. for (; j < layer_count; j++)
  1123. {
  1124. if (layers[j]->type != "Dropout")
  1125. continue;
  1126. if (layers[j]->bottoms.size() != 1)
  1127. continue;
  1128. if (layers[j]->bottoms[0] == top_blob_index)
  1129. break;
  1130. }
  1131. if (j == layer_count)
  1132. continue;
  1133. // fuse InnerProduct - Dropout to InnerProduct
  1134. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1135. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[j];
  1136. fprintf(stderr, "fuse_innerproduct_dropout %s %s\n", innerproduct->name.c_str(), dropout->name.c_str());
  1137. float scale = dropout->scale;
  1138. if (scale != 1.f)
  1139. {
  1140. const int num_output = innerproduct->num_output;
  1141. const int weight_per_outch = innerproduct->weight_data_size / num_output;
  1142. float* weight = innerproduct->weight_data;
  1143. for (int i = 0; i < num_output; i++)
  1144. {
  1145. float* conv_weight_outch = weight + weight_per_outch * i;
  1146. for (int j = 0; j < weight_per_outch; j++)
  1147. {
  1148. conv_weight_outch[j] *= scale;
  1149. }
  1150. }
  1151. if (innerproduct->bias_term)
  1152. {
  1153. float* bias = innerproduct->bias_data;
  1154. for (int i = 0; i < num_output; i++)
  1155. {
  1156. bias[i] *= scale;
  1157. }
  1158. }
  1159. }
  1160. int top_blob_index_final = dropout->tops[0];
  1161. innerproduct->tops[0] = top_blob_index_final;
  1162. blobs[top_blob_index_final].producer = i;
  1163. dropout->type = "ncnnfused";
  1164. }
  1165. return 0;
  1166. }
  1167. int NetOptimize::fuse_convolution_activation()
  1168. {
  1169. const size_t layer_count = layers.size();
  1170. for (size_t i = 0; i < layer_count; i++)
  1171. {
  1172. if (layers[i]->type != "Convolution")
  1173. continue;
  1174. // Convolution - Activation
  1175. int top_blob_index = layers[i]->tops[0];
  1176. size_t j = i + 1;
  1177. for (; j < layer_count; j++)
  1178. {
  1179. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid" && layers[j]->type != "Mish")
  1180. continue;
  1181. if (layers[j]->bottoms.size() != 1)
  1182. continue;
  1183. if (layers[j]->bottoms[0] == top_blob_index)
  1184. break;
  1185. }
  1186. if (j == layer_count)
  1187. continue;
  1188. // fuse Convolution - Activation to Convolution
  1189. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  1190. ncnn::Layer* activation = layers[j];
  1191. fprintf(stderr, "fuse_convolution_activation %s %s\n", convolution->name.c_str(), activation->name.c_str());
  1192. if (activation->type == "ReLU")
  1193. {
  1194. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1195. if (relu->slope == 0.f)
  1196. {
  1197. convolution->activation_type = 1;
  1198. }
  1199. else
  1200. {
  1201. convolution->activation_type = 2;
  1202. convolution->activation_params = ncnn::Mat(1);
  1203. convolution->activation_params[0] = relu->slope;
  1204. }
  1205. }
  1206. else if (activation->type == "Clip")
  1207. {
  1208. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1209. convolution->activation_type = 3;
  1210. convolution->activation_params = ncnn::Mat(2);
  1211. convolution->activation_params[0] = clip->min;
  1212. convolution->activation_params[1] = clip->max;
  1213. }
  1214. else if (activation->type == "Sigmoid")
  1215. {
  1216. convolution->activation_type = 4;
  1217. }
  1218. else if (activation->type == "Mish")
  1219. {
  1220. convolution->activation_type = 5;
  1221. }
  1222. int top_blob_index_final = activation->tops[0];
  1223. convolution->tops[0] = top_blob_index_final;
  1224. blobs[top_blob_index_final].producer = i;
  1225. activation->type = "ncnnfused";
  1226. }
  1227. return 0;
  1228. }
  1229. int NetOptimize::fuse_convolutiondepthwise_activation()
  1230. {
  1231. const size_t layer_count = layers.size();
  1232. for (size_t i = 0; i < layer_count; i++)
  1233. {
  1234. if (layers[i]->type != "ConvolutionDepthWise")
  1235. continue;
  1236. // ConvolutionDepthWise - Activation
  1237. int top_blob_index = layers[i]->tops[0];
  1238. size_t j = i + 1;
  1239. for (; j < layer_count; j++)
  1240. {
  1241. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid" && layers[j]->type != "Mish")
  1242. continue;
  1243. if (layers[j]->bottoms.size() != 1)
  1244. continue;
  1245. if (layers[j]->bottoms[0] == top_blob_index)
  1246. break;
  1247. }
  1248. if (j == layer_count)
  1249. continue;
  1250. // fuse ConvolutionDepthWise - Activation to ConvolutionDepthWise
  1251. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  1252. ncnn::Layer* activation = layers[j];
  1253. fprintf(stderr, "fuse_convolutiondepthwise_activation %s %s\n", convolutiondepthwise->name.c_str(), activation->name.c_str());
  1254. if (activation->type == "ReLU")
  1255. {
  1256. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1257. if (relu->slope == 0.f)
  1258. {
  1259. convolutiondepthwise->activation_type = 1;
  1260. }
  1261. else
  1262. {
  1263. convolutiondepthwise->activation_type = 2;
  1264. convolutiondepthwise->activation_params = ncnn::Mat(1);
  1265. convolutiondepthwise->activation_params[0] = relu->slope;
  1266. }
  1267. }
  1268. else if (activation->type == "Clip")
  1269. {
  1270. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1271. convolutiondepthwise->activation_type = 3;
  1272. convolutiondepthwise->activation_params = ncnn::Mat(2);
  1273. convolutiondepthwise->activation_params[0] = clip->min;
  1274. convolutiondepthwise->activation_params[1] = clip->max;
  1275. }
  1276. else if (activation->type == "Sigmoid")
  1277. {
  1278. convolutiondepthwise->activation_type = 4;
  1279. }
  1280. else if (activation->type == "Mish")
  1281. {
  1282. convolutiondepthwise->activation_type = 5;
  1283. }
  1284. int top_blob_index_final = activation->tops[0];
  1285. convolutiondepthwise->tops[0] = top_blob_index_final;
  1286. blobs[top_blob_index_final].producer = i;
  1287. activation->type = "ncnnfused";
  1288. }
  1289. return 0;
  1290. }
  1291. int NetOptimize::fuse_deconvolution_activation()
  1292. {
  1293. const size_t layer_count = layers.size();
  1294. for (size_t i = 0; i < layer_count; i++)
  1295. {
  1296. if (layers[i]->type != "Deconvolution")
  1297. continue;
  1298. // Deconvolution - Activation
  1299. int top_blob_index = layers[i]->tops[0];
  1300. size_t j = i + 1;
  1301. for (; j < layer_count; j++)
  1302. {
  1303. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1304. continue;
  1305. if (layers[j]->bottoms.size() != 1)
  1306. continue;
  1307. if (layers[j]->bottoms[0] == top_blob_index)
  1308. break;
  1309. }
  1310. if (j == layer_count)
  1311. continue;
  1312. // fuse Deconvolution - Activation to Deconvolution
  1313. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  1314. ncnn::Layer* activation = layers[j];
  1315. fprintf(stderr, "fuse_deconvolution_activation %s %s\n", deconvolution->name.c_str(), activation->name.c_str());
  1316. if (activation->type == "ReLU")
  1317. {
  1318. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1319. if (relu->slope == 0.f)
  1320. {
  1321. deconvolution->activation_type = 1;
  1322. }
  1323. else
  1324. {
  1325. deconvolution->activation_type = 2;
  1326. deconvolution->activation_params = ncnn::Mat(1);
  1327. deconvolution->activation_params[0] = relu->slope;
  1328. }
  1329. }
  1330. else if (activation->type == "Clip")
  1331. {
  1332. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1333. deconvolution->activation_type = 3;
  1334. deconvolution->activation_params = ncnn::Mat(2);
  1335. deconvolution->activation_params[0] = clip->min;
  1336. deconvolution->activation_params[1] = clip->max;
  1337. }
  1338. else if (activation->type == "Sigmoid")
  1339. {
  1340. deconvolution->activation_type = 4;
  1341. }
  1342. int top_blob_index_final = activation->tops[0];
  1343. deconvolution->tops[0] = top_blob_index_final;
  1344. blobs[top_blob_index_final].producer = i;
  1345. activation->type = "ncnnfused";
  1346. }
  1347. return 0;
  1348. }
  1349. int NetOptimize::fuse_deconvolutiondepthwise_activation()
  1350. {
  1351. const size_t layer_count = layers.size();
  1352. for (size_t i = 0; i < layer_count; i++)
  1353. {
  1354. if (layers[i]->type != "DeconvolutionDepthWise")
  1355. continue;
  1356. // DeconvolutionDepthWise - Activation
  1357. int top_blob_index = layers[i]->tops[0];
  1358. size_t j = i + 1;
  1359. for (; j < layer_count; j++)
  1360. {
  1361. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1362. continue;
  1363. if (layers[j]->bottoms.size() != 1)
  1364. continue;
  1365. if (layers[j]->bottoms[0] == top_blob_index)
  1366. break;
  1367. }
  1368. if (j == layer_count)
  1369. continue;
  1370. // fuse DeconvolutionDepthWise - Activation to DeconvolutionDepthWise
  1371. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  1372. ncnn::Layer* activation = layers[j];
  1373. fprintf(stderr, "fuse_deconvolutiondepthwise_activation %s %s\n", deconvolutiondepthwise->name.c_str(), activation->name.c_str());
  1374. if (activation->type == "ReLU")
  1375. {
  1376. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1377. if (relu->slope == 0.f)
  1378. {
  1379. deconvolutiondepthwise->activation_type = 1;
  1380. }
  1381. else
  1382. {
  1383. deconvolutiondepthwise->activation_type = 2;
  1384. deconvolutiondepthwise->activation_params = ncnn::Mat(1);
  1385. deconvolutiondepthwise->activation_params[0] = relu->slope;
  1386. }
  1387. }
  1388. else if (activation->type == "Clip")
  1389. {
  1390. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1391. deconvolutiondepthwise->activation_type = 3;
  1392. deconvolutiondepthwise->activation_params = ncnn::Mat(2);
  1393. deconvolutiondepthwise->activation_params[0] = clip->min;
  1394. deconvolutiondepthwise->activation_params[1] = clip->max;
  1395. }
  1396. else if (activation->type == "Sigmoid")
  1397. {
  1398. deconvolutiondepthwise->activation_type = 4;
  1399. }
  1400. int top_blob_index_final = activation->tops[0];
  1401. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  1402. blobs[top_blob_index_final].producer = i;
  1403. activation->type = "ncnnfused";
  1404. }
  1405. return 0;
  1406. }
  1407. int NetOptimize::fuse_innerproduct_activation()
  1408. {
  1409. const size_t layer_count = layers.size();
  1410. for (size_t i = 0; i < layer_count; i++)
  1411. {
  1412. if (layers[i]->type != "InnerProduct")
  1413. continue;
  1414. // InnerProduct - Activation
  1415. int top_blob_index = layers[i]->tops[0];
  1416. size_t j = i + 1;
  1417. for (; j < layer_count; j++)
  1418. {
  1419. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1420. continue;
  1421. if (layers[j]->bottoms.size() != 1)
  1422. continue;
  1423. if (layers[j]->bottoms[0] == top_blob_index)
  1424. break;
  1425. }
  1426. if (j == layer_count)
  1427. continue;
  1428. // fuse InnerProduct - Activation to InnerProduct
  1429. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1430. ncnn::Layer* activation = layers[j];
  1431. fprintf(stderr, "fuse_innerproduct_activation %s %s\n", innerproduct->name.c_str(), activation->name.c_str());
  1432. if (activation->type == "ReLU")
  1433. {
  1434. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1435. if (relu->slope == 0.f)
  1436. {
  1437. innerproduct->activation_type = 1;
  1438. }
  1439. else
  1440. {
  1441. innerproduct->activation_type = 2;
  1442. innerproduct->activation_params = ncnn::Mat(1);
  1443. innerproduct->activation_params[0] = relu->slope;
  1444. }
  1445. }
  1446. else if (activation->type == "Clip")
  1447. {
  1448. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1449. innerproduct->activation_type = 3;
  1450. innerproduct->activation_params = ncnn::Mat(2);
  1451. innerproduct->activation_params[0] = clip->min;
  1452. innerproduct->activation_params[1] = clip->max;
  1453. }
  1454. else if (activation->type == "Sigmoid")
  1455. {
  1456. innerproduct->activation_type = 4;
  1457. }
  1458. int top_blob_index_final = activation->tops[0];
  1459. innerproduct->tops[0] = top_blob_index_final;
  1460. blobs[top_blob_index_final].producer = i;
  1461. activation->type = "ncnnfused";
  1462. }
  1463. return 0;
  1464. }
  1465. int NetOptimize::fuse_memorydata_binaryop()
  1466. {
  1467. const size_t layer_count = layers.size();
  1468. for (size_t i = 0; i < layer_count; i++)
  1469. {
  1470. if (layers[i]->type != "MemoryData")
  1471. continue;
  1472. // MemoryData - BinaryOp
  1473. int top_blob_index = layers[i]->tops[0];
  1474. size_t j = i + 1;
  1475. for (; j < layer_count; j++)
  1476. {
  1477. if (layers[j]->type != "BinaryOp")
  1478. continue;
  1479. if (layers[j]->bottoms.size() != 2)
  1480. continue;
  1481. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1482. break;
  1483. }
  1484. if (j == layer_count)
  1485. continue;
  1486. // fuse MemoryData - BinaryOp to BinaryOp
  1487. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[i];
  1488. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1489. if (memorydata->w != 1 || memorydata->h != 0 || memorydata->c != 0)
  1490. {
  1491. // not a scalar
  1492. continue;
  1493. }
  1494. int memorydata_index = 1;
  1495. if (binaryop->bottoms[0] == top_blob_index)
  1496. {
  1497. int op_type = binaryop->op_type;
  1498. if (op_type == ncnn::BinaryOp::Operation_ADD
  1499. || op_type == ncnn::BinaryOp::Operation_MUL
  1500. || op_type == ncnn::BinaryOp::Operation_MAX
  1501. || op_type == ncnn::BinaryOp::Operation_MIN)
  1502. {
  1503. memorydata_index = 0;
  1504. }
  1505. else if (op_type == ncnn::BinaryOp::Operation_SUB)
  1506. {
  1507. binaryop->op_type = ncnn::BinaryOp::Operation_RSUB;
  1508. memorydata_index = 0;
  1509. }
  1510. else if (op_type == ncnn::BinaryOp::Operation_DIV)
  1511. {
  1512. binaryop->op_type = ncnn::BinaryOp::Operation_RDIV;
  1513. memorydata_index = 0;
  1514. }
  1515. else
  1516. {
  1517. // non interchangeable binaryop
  1518. continue;
  1519. }
  1520. }
  1521. float scalar = memorydata->data[0];
  1522. binaryop->with_scalar = 1;
  1523. binaryop->b = scalar;
  1524. fprintf(stderr, "fuse_memorydata_binaryop %s %s\n", memorydata->name.c_str(), binaryop->name.c_str());
  1525. binaryop->bottoms.erase(binaryop->bottoms.begin() + memorydata_index);
  1526. memorydata->type = "ncnnfused";
  1527. }
  1528. for (size_t i = 0; i < layer_count; i++)
  1529. {
  1530. if (layers[i]->type != "MemoryData")
  1531. continue;
  1532. // MemoryData - Split - BinaryOp
  1533. int top_blob_index = layers[i]->tops[0];
  1534. size_t j0 = i + 1;
  1535. for (; j0 < layer_count; j0++)
  1536. {
  1537. if (layers[j0]->type != "Split")
  1538. continue;
  1539. if (layers[j0]->bottoms.size() != 1)
  1540. continue;
  1541. if (layers[j0]->bottoms[0] == top_blob_index)
  1542. break;
  1543. }
  1544. if (j0 == layer_count)
  1545. continue;
  1546. int split_top_blob_index = -1;
  1547. size_t j1 = j0 + 1;
  1548. for (; j1 < layer_count; j1++)
  1549. {
  1550. if (layers[j1]->type != "BinaryOp")
  1551. continue;
  1552. if (layers[j1]->bottoms.size() != 2)
  1553. continue;
  1554. for (int k = 0; k < (int)layers[j0]->tops.size(); k++)
  1555. {
  1556. if (layers[j1]->bottoms[0] == layers[j0]->tops[k] || layers[j1]->bottoms[1] == layers[j0]->tops[k])
  1557. {
  1558. split_top_blob_index = k;
  1559. break;
  1560. }
  1561. }
  1562. if (split_top_blob_index != -1)
  1563. break;
  1564. }
  1565. if (j1 == layer_count)
  1566. continue;
  1567. // fuse MemoryData - Split - BinaryOp to BinaryOp
  1568. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[i];
  1569. ncnn::Split* split = (ncnn::Split*)layers[j0];
  1570. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j1];
  1571. if (memorydata->w != 1 || memorydata->h != 0 || memorydata->c != 0)
  1572. {
  1573. // not a scalar
  1574. continue;
  1575. }
  1576. int memorydata_index = 1;
  1577. if (binaryop->bottoms[0] == split->tops[split_top_blob_index])
  1578. {
  1579. int op_type = binaryop->op_type;
  1580. if (op_type == ncnn::BinaryOp::Operation_ADD
  1581. || op_type == ncnn::BinaryOp::Operation_MUL
  1582. || op_type == ncnn::BinaryOp::Operation_MAX
  1583. || op_type == ncnn::BinaryOp::Operation_MIN)
  1584. {
  1585. memorydata_index = 0;
  1586. }
  1587. else if (op_type == ncnn::BinaryOp::Operation_SUB)
  1588. {
  1589. binaryop->op_type = ncnn::BinaryOp::Operation_RSUB;
  1590. memorydata_index = 0;
  1591. }
  1592. else if (op_type == ncnn::BinaryOp::Operation_DIV)
  1593. {
  1594. binaryop->op_type = ncnn::BinaryOp::Operation_RDIV;
  1595. memorydata_index = 0;
  1596. }
  1597. else
  1598. {
  1599. // non interchangeable binaryop
  1600. continue;
  1601. }
  1602. }
  1603. float scalar = memorydata->data[0];
  1604. binaryop->with_scalar = 1;
  1605. binaryop->b = scalar;
  1606. fprintf(stderr, "fuse_memorydata_binaryop %s %s\n", memorydata->name.c_str(), binaryop->name.c_str());
  1607. binaryop->bottoms.erase(binaryop->bottoms.begin() + memorydata_index);
  1608. split->tops.erase(split->tops.begin() + split_top_blob_index);
  1609. if (split->tops.empty())
  1610. {
  1611. split->type = "ncnnfused";
  1612. memorydata->type = "ncnnfused";
  1613. }
  1614. i--;
  1615. }
  1616. return 0;
  1617. }
  1618. int NetOptimize::fuse_binaryop_eltwise()
  1619. {
  1620. const size_t layer_count = layers.size();
  1621. for (size_t i = 0; i < layer_count; i++)
  1622. {
  1623. if (layers[i]->type != "BinaryOp")
  1624. continue;
  1625. if (layers[i]->bottoms.size() != 2)
  1626. continue;
  1627. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[i];
  1628. if (binaryop->op_type != ncnn::BinaryOp::Operation_ADD)
  1629. continue;
  1630. if (binaryop->with_scalar)
  1631. continue;
  1632. // BinaryOp - BinaryOp - BinaryOp
  1633. int bottom_blob_index_0 = binaryop->bottoms[0];
  1634. int bottom_blob_index_1 = binaryop->bottoms[1];
  1635. size_t j0 = 0;
  1636. for (; j0 < i; j0++)
  1637. {
  1638. if (layers[j0]->type != "BinaryOp")
  1639. continue;
  1640. if (layers[j0]->bottoms.size() != 1)
  1641. continue;
  1642. if (((ncnn::BinaryOp*)layers[j0])->op_type != ncnn::BinaryOp::Operation_MUL)
  1643. continue;
  1644. if (layers[j0]->tops[0] == bottom_blob_index_0)
  1645. break;
  1646. }
  1647. size_t j1 = 0;
  1648. for (; j1 < i; j1++)
  1649. {
  1650. if (layers[j1]->type != "BinaryOp")
  1651. continue;
  1652. if (layers[j1]->bottoms.size() != 1)
  1653. continue;
  1654. if (((ncnn::BinaryOp*)layers[j1])->op_type != ncnn::BinaryOp::Operation_MUL)
  1655. continue;
  1656. if (layers[j1]->tops[0] == bottom_blob_index_1)
  1657. break;
  1658. }
  1659. if (j0 == i && j1 == i)
  1660. continue;
  1661. ncnn::BinaryOp* binaryop0 = (ncnn::BinaryOp*)layers[j0];
  1662. ncnn::BinaryOp* binaryop1 = (ncnn::BinaryOp*)layers[j1];
  1663. fprintf(stderr, "fuse_binaryop_eltwise %s %s %s\n", binaryop0->name.c_str(), binaryop1->name.c_str(), binaryop->name.c_str());
  1664. ncnn::Eltwise* eltwise = (ncnn::Eltwise*)ncnn::create_layer("Eltwise");
  1665. eltwise->type = "Eltwise";
  1666. eltwise->name = binaryop->name;
  1667. eltwise->bottoms = binaryop->bottoms;
  1668. eltwise->tops = binaryop->tops;
  1669. ncnn::ParamDict pd;
  1670. eltwise->load_param(pd);
  1671. eltwise->op_type = ncnn::Eltwise::Operation_SUM;
  1672. eltwise->coeffs = ncnn::Mat(2);
  1673. if (j0 != i && j1 != i)
  1674. {
  1675. // fuse BinaryOp - BinaryOp - BinaryOp to Eltwise
  1676. eltwise->coeffs[0] = binaryop0->b;
  1677. eltwise->coeffs[1] = binaryop1->b;
  1678. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1679. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1680. binaryop0->type = "ncnnfused";
  1681. binaryop1->type = "ncnnfused";
  1682. }
  1683. if (j0 != i && j1 == i)
  1684. {
  1685. // fuse BinaryOp - X - BinaryOp to Eltwise
  1686. eltwise->coeffs[0] = binaryop0->b;
  1687. eltwise->coeffs[1] = 1.f;
  1688. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1689. binaryop0->type = "ncnnfused";
  1690. }
  1691. if (j0 == i && j1 != i)
  1692. {
  1693. // fuse X - BinaryOp - BinaryOp to Eltwise
  1694. eltwise->coeffs[0] = 1.f;
  1695. eltwise->coeffs[1] = binaryop1->b;
  1696. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1697. binaryop1->type = "ncnnfused";
  1698. }
  1699. layers[i] = eltwise;
  1700. delete binaryop;
  1701. }
  1702. return 0;
  1703. }
  1704. int NetOptimize::eliminate_dropout()
  1705. {
  1706. const size_t layer_count = layers.size();
  1707. for (size_t i = 0; i < layer_count; i++)
  1708. {
  1709. if (layers[i]->type != "Dropout")
  1710. continue;
  1711. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[i];
  1712. if (dropout->scale != 1.f)
  1713. continue;
  1714. // Any - Dropout
  1715. int bottom_blob_index = layers[i]->bottoms[0];
  1716. int j = i - 1;
  1717. for (; j >= 0; j--)
  1718. {
  1719. if (layers[j]->type == "ncnnfused")
  1720. continue;
  1721. if (layers[j]->tops.size() != 1)
  1722. continue;
  1723. if (layers[j]->tops[0] == bottom_blob_index)
  1724. break;
  1725. }
  1726. if (j == -1)
  1727. continue;
  1728. ncnn::Layer* any = layers[j];
  1729. fprintf(stderr, "eliminate_dropout %s %s\n", any->name.c_str(), dropout->name.c_str());
  1730. int top_blob_index_final = dropout->tops[0];
  1731. any->tops[0] = top_blob_index_final;
  1732. blobs[top_blob_index_final].producer = j;
  1733. dropout->type = "ncnnfused";
  1734. }
  1735. return 0;
  1736. }
  1737. int NetOptimize::eliminate_pooling1x1()
  1738. {
  1739. const size_t layer_count = layers.size();
  1740. for (size_t i = 0; i < layer_count; i++)
  1741. {
  1742. if (layers[i]->type != "Pooling")
  1743. continue;
  1744. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1745. if (pooling->pad_left != 0 || pooling->pad_right != 0 || pooling->pad_top != 0 || pooling->pad_bottom != 0)
  1746. continue;
  1747. if (pooling->kernel_w != 1 || pooling->kernel_h != 1 || pooling->stride_w != 1 || pooling->stride_h != 1)
  1748. continue;
  1749. if (pooling->global_pooling != 0)
  1750. continue;
  1751. // Any - Pooling
  1752. int bottom_blob_index = layers[i]->bottoms[0];
  1753. int top_i = -1;
  1754. int j = i - 1;
  1755. for (; j >= 0; j--)
  1756. {
  1757. if (layers[j]->type == "ncnnfused")
  1758. continue;
  1759. for (size_t k = 0; k < layers[j]->tops.size(); k++)
  1760. {
  1761. if (layers[j]->tops[k] == bottom_blob_index)
  1762. {
  1763. top_i = k;
  1764. break;
  1765. }
  1766. }
  1767. if (top_i != -1)
  1768. break;
  1769. }
  1770. if (j == -1)
  1771. continue;
  1772. ncnn::Layer* any = layers[j];
  1773. fprintf(stderr, "eliminate_pooling1x1 %s %s\n", any->name.c_str(), pooling->name.c_str());
  1774. int top_blob_index_final = pooling->tops[0];
  1775. any->tops[top_i] = top_blob_index_final;
  1776. blobs[top_blob_index_final].producer = j;
  1777. pooling->type = "ncnnfused";
  1778. }
  1779. return 0;
  1780. }
  1781. int NetOptimize::eliminate_noop()
  1782. {
  1783. const size_t layer_count = layers.size();
  1784. for (size_t i = 0; i < layer_count; i++)
  1785. {
  1786. if (layers[i]->type != "Noop")
  1787. continue;
  1788. ncnn::Layer* noop = layers[i];
  1789. if (noop->bottoms.empty())
  1790. {
  1791. // Noop
  1792. fprintf(stderr, "eliminate_noop %s\n", noop->name.c_str());
  1793. size_t top_blob_count = noop->tops.size();
  1794. for (size_t k = 0; k < top_blob_count; k++)
  1795. {
  1796. int top_blob_index_final = noop->tops[k];
  1797. blobs[top_blob_index_final].producer = -1;
  1798. }
  1799. noop->type = "ncnnfused";
  1800. continue;
  1801. }
  1802. // Any - Noop
  1803. int bottom_blob_index = layers[i]->bottoms[0];
  1804. int j = i - 1;
  1805. for (; j >= 0; j--)
  1806. {
  1807. if (layers[j]->type == "ncnnfused")
  1808. continue;
  1809. if (layers[j]->tops.size() != 1)
  1810. continue;
  1811. if (layers[j]->tops[0] == bottom_blob_index)
  1812. break;
  1813. }
  1814. if (j == -1)
  1815. continue;
  1816. ncnn::Layer* any = layers[j];
  1817. fprintf(stderr, "eliminate_noop %s %s\n", any->name.c_str(), noop->name.c_str());
  1818. size_t top_blob_count = std::min(noop->tops.size(), any->tops.size());
  1819. for (size_t k = 0; k < top_blob_count; k++)
  1820. {
  1821. int top_blob_index_final = noop->tops[k];
  1822. any->tops[k] = top_blob_index_final;
  1823. blobs[top_blob_index_final].producer = j;
  1824. }
  1825. noop->type = "ncnnfused";
  1826. }
  1827. return 0;
  1828. }
  1829. int NetOptimize::eliminate_orphaned_memorydata()
  1830. {
  1831. const size_t layer_count = layers.size();
  1832. for (size_t i = 0; i < layer_count; i++)
  1833. {
  1834. if (layers[i]->type != "MemoryData")
  1835. continue;
  1836. // MemoryData - X
  1837. int top_blob_index = layers[i]->tops[0];
  1838. size_t j = i + 1;
  1839. for (; j < layer_count; j++)
  1840. {
  1841. if (layers[j]->type == "ncnnfused")
  1842. continue;
  1843. bool orphaned = true;
  1844. for (size_t k = 0; k < layers[j]->bottoms.size(); k++)
  1845. {
  1846. if (layers[j]->bottoms[k] == top_blob_index)
  1847. {
  1848. orphaned = false;
  1849. break;
  1850. }
  1851. }
  1852. if (!orphaned)
  1853. break;
  1854. }
  1855. if (j < layer_count)
  1856. continue;
  1857. // assert orphaned == true
  1858. fprintf(stderr, "eliminate_orphaned_memorydata %s\n", layers[i]->name.c_str());
  1859. layers[i]->type = "ncnnfused";
  1860. }
  1861. return 0;
  1862. }
  1863. int NetOptimize::eliminate_reshape_after_global_pooling()
  1864. {
  1865. const size_t layer_count = layers.size();
  1866. for (size_t i = 0; i < layer_count; i++)
  1867. {
  1868. if (layers[i]->type != "Pooling")
  1869. continue;
  1870. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1871. if (pooling->global_pooling == 0)
  1872. continue;
  1873. // Pooling - Reshape
  1874. int top_blob_index = layers[i]->tops[0];
  1875. size_t j = i + 1;
  1876. for (; j < layer_count; j++)
  1877. {
  1878. if (layers[j]->type != "Reshape")
  1879. continue;
  1880. if (layers[j]->bottoms.size() != 1)
  1881. continue;
  1882. if (layers[j]->bottoms[0] == top_blob_index)
  1883. break;
  1884. }
  1885. if (j == layer_count)
  1886. continue;
  1887. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[j];
  1888. if (reshape->h != -233 || reshape->c != -233 || reshape->permute != 0)
  1889. continue;
  1890. fprintf(stderr, "eliminate_reshape_after_global_pooling %s %s\n", pooling->name.c_str(), reshape->name.c_str());
  1891. int top_blob_index_final = reshape->tops[0];
  1892. pooling->tops[0] = top_blob_index_final;
  1893. blobs[top_blob_index_final].producer = i;
  1894. reshape->type = "ncnnfused";
  1895. }
  1896. return 0;
  1897. }
  1898. int NetOptimize::eliminate_flatten_after_global_pooling()
  1899. {
  1900. const size_t layer_count = layers.size();
  1901. for (size_t i = 0; i < layer_count; i++)
  1902. {
  1903. if (layers[i]->type != "Pooling")
  1904. continue;
  1905. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1906. if (pooling->global_pooling == 0)
  1907. continue;
  1908. // Pooling - Flatten
  1909. int top_blob_index = layers[i]->tops[0];
  1910. size_t j = i + 1;
  1911. for (; j < layer_count; j++)
  1912. {
  1913. if (layers[j]->type != "Flatten")
  1914. continue;
  1915. if (layers[j]->bottoms.size() != 1)
  1916. continue;
  1917. if (layers[j]->bottoms[0] == top_blob_index)
  1918. break;
  1919. }
  1920. if (j == layer_count)
  1921. continue;
  1922. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1923. fprintf(stderr, "eliminate_flatten_after_global_pooling %s %s\n", pooling->name.c_str(), flatten->name.c_str());
  1924. int top_blob_index_final = flatten->tops[0];
  1925. pooling->tops[0] = top_blob_index_final;
  1926. blobs[top_blob_index_final].producer = i;
  1927. flatten->type = "ncnnfused";
  1928. }
  1929. return 0;
  1930. }
  1931. int NetOptimize::eliminate_flatten_after_innerproduct()
  1932. {
  1933. const size_t layer_count = layers.size();
  1934. for (size_t i = 0; i < layer_count; i++)
  1935. {
  1936. if (layers[i]->type != "InnerProduct")
  1937. continue;
  1938. // InnerProduct - Flatten
  1939. int top_blob_index = layers[i]->tops[0];
  1940. size_t j = i + 1;
  1941. for (; j < layer_count; j++)
  1942. {
  1943. if (layers[j]->type != "Flatten")
  1944. continue;
  1945. if (layers[j]->bottoms.size() != 1)
  1946. continue;
  1947. if (layers[j]->bottoms[0] == top_blob_index)
  1948. break;
  1949. }
  1950. if (j == layer_count)
  1951. continue;
  1952. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1953. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1954. fprintf(stderr, "eliminate_flatten_after_innerproduct %s %s\n", innerproduct->name.c_str(), flatten->name.c_str());
  1955. int top_blob_index_final = flatten->tops[0];
  1956. innerproduct->tops[0] = top_blob_index_final;
  1957. blobs[top_blob_index_final].producer = i;
  1958. flatten->type = "ncnnfused";
  1959. }
  1960. return 0;
  1961. }
  1962. int NetOptimize::eliminate_reshape_before_binaryop()
  1963. {
  1964. const size_t layer_count = layers.size();
  1965. for (size_t i = 0; i < layer_count; i++)
  1966. {
  1967. if (layers[i]->type != "Reshape")
  1968. continue;
  1969. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[i];
  1970. if (reshape->w != 1 || reshape->h != 1 || reshape->permute != 0)
  1971. continue;
  1972. // Reshape - BinaryOp
  1973. int top_blob_index = layers[i]->tops[0];
  1974. size_t j = i + 1;
  1975. for (; j < layer_count; j++)
  1976. {
  1977. if (layers[j]->type != "BinaryOp")
  1978. continue;
  1979. if (layers[j]->bottoms.size() != 2)
  1980. continue;
  1981. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1982. break;
  1983. }
  1984. if (j == layer_count)
  1985. continue;
  1986. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1987. fprintf(stderr, "eliminate_reshape_before_binaryop %s %s\n", reshape->name.c_str(), binaryop->name.c_str());
  1988. int bottom_blob_index_final = reshape->bottoms[0];
  1989. if (layers[j]->bottoms[0] == top_blob_index)
  1990. binaryop->bottoms[0] = bottom_blob_index_final;
  1991. if (layers[j]->bottoms[1] == top_blob_index)
  1992. binaryop->bottoms[1] = bottom_blob_index_final;
  1993. blobs[bottom_blob_index_final].consumer = j;
  1994. reshape->type = "ncnnfused";
  1995. }
  1996. return 0;
  1997. }
  1998. int NetOptimize::replace_reduction_with_global_pooling()
  1999. {
  2000. const size_t layer_count = layers.size();
  2001. for (size_t i = 0; i < layer_count; i++)
  2002. {
  2003. if (layers[i]->type != "Reduction")
  2004. continue;
  2005. ncnn::Reduction* reduction1 = (ncnn::Reduction*)layers[i];
  2006. if (reduction1->operation != 3 || reduction1->reduce_all != 0 || reduction1->coeff != 1.f)
  2007. continue;
  2008. if (reduction1->axes.w != 1)
  2009. continue;
  2010. const int* axes_ptr = reduction1->axes;
  2011. if (axes_ptr[0] != 2 && axes_ptr[0] != 3)
  2012. continue;
  2013. // Reduction(2/3) - Reduction(2)
  2014. int top_blob_index = layers[i]->tops[0];
  2015. size_t j = i + 1;
  2016. for (; j < layer_count; j++)
  2017. {
  2018. if (layers[j]->type != "Reduction")
  2019. continue;
  2020. if (layers[j]->bottoms.size() != 1)
  2021. continue;
  2022. if (layers[j]->bottoms[0] == top_blob_index)
  2023. break;
  2024. }
  2025. if (j == layer_count)
  2026. continue;
  2027. ncnn::Reduction* reduction2 = (ncnn::Reduction*)layers[j];
  2028. if (reduction2->operation != 3 || reduction2->reduce_all != 0 || reduction2->coeff != 1.f)
  2029. continue;
  2030. if (reduction2->axes.w != 1)
  2031. continue;
  2032. const int* axes2_ptr = reduction2->axes;
  2033. if (axes2_ptr[0] != 2)
  2034. continue;
  2035. fprintf(stderr, "replace_reduction_with_global_pooling %s %s\n", reduction1->name.c_str(), reduction2->name.c_str());
  2036. ncnn::Pooling* pooling = (ncnn::Pooling*)ncnn::create_layer("Pooling");
  2037. pooling->type = "Pooling";
  2038. pooling->name = reduction2->name;
  2039. pooling->bottoms = reduction2->bottoms;
  2040. pooling->tops = reduction2->tops;
  2041. ncnn::ParamDict pd;
  2042. pooling->load_param(pd);
  2043. pooling->pooling_type = 1;
  2044. pooling->global_pooling = 1;
  2045. layers[j] = pooling;
  2046. delete reduction2;
  2047. int bottom_blob_index_final = reduction1->bottoms[0];
  2048. pooling->bottoms[0] = bottom_blob_index_final;
  2049. blobs[bottom_blob_index_final].consumer = j;
  2050. reduction1->type = "ncnnfused";
  2051. }
  2052. return 0;
  2053. }
  2054. int NetOptimize::replace_prelu_with_leaky_relu()
  2055. {
  2056. const size_t layer_count = layers.size();
  2057. for (size_t i = 0; i < layer_count; i++)
  2058. {
  2059. if (layers[i]->type != "PReLU")
  2060. continue;
  2061. ncnn::PReLU* prelu = (ncnn::PReLU*)layers[i];
  2062. if (prelu->num_slope != 1)
  2063. continue;
  2064. fprintf(stderr, "replace_prelu_with_leaky_relu %s\n", prelu->name.c_str());
  2065. ncnn::ReLU* relu = (ncnn::ReLU*)ncnn::create_layer("ReLU");
  2066. relu->type = "ReLU";
  2067. relu->name = prelu->name;
  2068. relu->bottoms = prelu->bottoms;
  2069. relu->tops = prelu->tops;
  2070. ncnn::ParamDict pd;
  2071. relu->load_param(pd);
  2072. relu->slope = prelu->slope_data[0];
  2073. layers[i] = relu;
  2074. delete prelu;
  2075. }
  2076. return 0;
  2077. }
  2078. int NetOptimize::replace_convolution_with_innerproduct_after_global_pooling()
  2079. {
  2080. const size_t layer_count = layers.size();
  2081. for (size_t i = 0; i < layer_count; i++)
  2082. {
  2083. if (layers[i]->type != "Pooling")
  2084. continue;
  2085. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  2086. if (pooling->global_pooling == 0)
  2087. continue;
  2088. // Pooling - Convolution
  2089. int top_blob_index = layers[i]->tops[0];
  2090. size_t j = i + 1;
  2091. for (; j < layer_count; j++)
  2092. {
  2093. if (layers[j]->type != "Convolution")
  2094. continue;
  2095. if (layers[j]->bottoms.size() != 1)
  2096. continue;
  2097. if (layers[j]->bottoms[0] == top_blob_index)
  2098. break;
  2099. }
  2100. if (j == layer_count)
  2101. continue;
  2102. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  2103. fprintf(stderr, "replace_convolution_with_innerproduct_after_global_pooling %s %s\n", pooling->name.c_str(), convolution->name.c_str());
  2104. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  2105. innerproduct->type = "InnerProduct";
  2106. innerproduct->name = convolution->name;
  2107. innerproduct->bottoms = convolution->bottoms;
  2108. innerproduct->tops = convolution->tops;
  2109. ncnn::ParamDict pd;
  2110. innerproduct->load_param(pd);
  2111. innerproduct->num_output = convolution->num_output;
  2112. innerproduct->bias_term = convolution->bias_term;
  2113. innerproduct->weight_data_size = convolution->weight_data_size;
  2114. innerproduct->int8_scale_term = convolution->int8_scale_term;
  2115. innerproduct->weight_data = convolution->weight_data;
  2116. innerproduct->bias_data = convolution->bias_data;
  2117. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  2118. innerproduct->bottom_blob_int8_scale = convolution->bottom_blob_int8_scale;
  2119. innerproduct->activation_type = convolution->activation_type;
  2120. innerproduct->activation_params = convolution->activation_params;
  2121. layers[j] = innerproduct;
  2122. delete convolution;
  2123. }
  2124. return 0;
  2125. }
  2126. int NetOptimize::replace_convolution_with_innerproduct_after_innerproduct()
  2127. {
  2128. const size_t layer_count = layers.size();
  2129. for (;;)
  2130. {
  2131. bool replaced = false;
  2132. for (size_t i = 0; i < layer_count; i++)
  2133. {
  2134. if (layers[i]->type != "InnerProduct")
  2135. continue;
  2136. // InnerProduct - Convolution
  2137. int top_blob_index = layers[i]->tops[0];
  2138. size_t j = i + 1;
  2139. for (; j < layer_count; j++)
  2140. {
  2141. if (layers[j]->type != "Convolution")
  2142. continue;
  2143. if (layers[j]->bottoms.size() != 1)
  2144. continue;
  2145. if (layers[j]->bottoms[0] == top_blob_index)
  2146. break;
  2147. }
  2148. if (j == layer_count)
  2149. continue;
  2150. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  2151. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  2152. fprintf(stderr, "replace_convolution_with_innerproduct_after_innerproduct %s %s\n", innerproduct->name.c_str(), convolution->name.c_str());
  2153. ncnn::InnerProduct* innerproduct2 = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  2154. innerproduct2->type = "InnerProduct";
  2155. innerproduct2->name = convolution->name;
  2156. innerproduct2->bottoms = convolution->bottoms;
  2157. innerproduct2->tops = convolution->tops;
  2158. ncnn::ParamDict pd;
  2159. innerproduct2->load_param(pd);
  2160. innerproduct2->num_output = convolution->num_output;
  2161. innerproduct2->bias_term = convolution->bias_term;
  2162. innerproduct2->weight_data_size = convolution->weight_data_size;
  2163. innerproduct->int8_scale_term = convolution->int8_scale_term;
  2164. innerproduct2->weight_data = convolution->weight_data;
  2165. innerproduct2->bias_data = convolution->bias_data;
  2166. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  2167. innerproduct->bottom_blob_int8_scale = convolution->bottom_blob_int8_scale;
  2168. innerproduct2->activation_type = convolution->activation_type;
  2169. innerproduct2->activation_params = convolution->activation_params;
  2170. layers[j] = innerproduct2;
  2171. delete convolution;
  2172. replaced = true;
  2173. }
  2174. if (!replaced)
  2175. break;
  2176. }
  2177. return 0;
  2178. }
  2179. int NetOptimize::shape_inference()
  2180. {
  2181. if (has_custom_layer)
  2182. {
  2183. fprintf(stderr, "model has custom layer, shape_inference skipped\n");
  2184. return -1;
  2185. }
  2186. const size_t layer_count = layers.size();
  2187. const size_t blob_count = blobs.size();
  2188. ncnn::Extractor ex = create_extractor();
  2189. // prepare Input blobs
  2190. for (size_t i = 0; i < layer_count; i++)
  2191. {
  2192. const ncnn::Layer* layer = layers[i];
  2193. if (layer->type == "ncnnfused")
  2194. continue;
  2195. if (layer->type != "Input")
  2196. continue;
  2197. ncnn::Input* input = (ncnn::Input*)layer;
  2198. int w = input->w;
  2199. int h = input->h;
  2200. int c = input->c;
  2201. int dims = 0;
  2202. if (w == 0 && h == 0 && c == 0) dims = 0;
  2203. if (w != 0 && h == 0 && c == 0) dims = 1;
  2204. if (w != 0 && h != 0 && c == 0) dims = 2;
  2205. if (w != 0 && h != 0 && c != 0) dims = 3;
  2206. if (dims == 0)
  2207. {
  2208. fprintf(stderr, "Input layer %s without shape info, shape_inference skipped\n", layer->name.c_str());
  2209. return -1;
  2210. }
  2211. ncnn::Mat m;
  2212. if (dims == 1) m.create(w);
  2213. if (dims == 2) m.create(w, h);
  2214. if (dims == 3) m.create(w, h, c);
  2215. ex.input(layer->tops[0], m);
  2216. }
  2217. // prepare blobs with predefined shape
  2218. for (size_t i = 0; i < blob_count; i++)
  2219. {
  2220. const ncnn::Blob& blob = blobs[i];
  2221. int dims = blob.shape.dims;
  2222. int w = blob.shape.w;
  2223. int h = blob.shape.h;
  2224. int c = blob.shape.c;
  2225. if (dims == 0)
  2226. continue;
  2227. ncnn::Mat m;
  2228. if (dims == 1) m.create(w);
  2229. if (dims == 2) m.create(w, h);
  2230. if (dims == 3) m.create(w, h, c);
  2231. ex.input(int(i), m);
  2232. }
  2233. fprintf(stderr, "shape_inference\n");
  2234. // resolve all layer output blob shape
  2235. for (size_t i = 0; i < layer_count; i++)
  2236. {
  2237. const ncnn::Layer* layer = layers[i];
  2238. if (layer->type == "ncnnfused")
  2239. continue;
  2240. for (size_t j = 0; j < layer->tops.size(); j++)
  2241. {
  2242. int top_blob_index = layer->tops[j];
  2243. ncnn::Mat m;
  2244. ex.extract(top_blob_index, m);
  2245. blobs[top_blob_index].shape = m;
  2246. }
  2247. }
  2248. // assign all layer blob shape
  2249. for (size_t i = 0; i < layer_count; i++)
  2250. {
  2251. ncnn::Layer* layer = layers[i];
  2252. if (layer->type == "ncnnfused")
  2253. continue;
  2254. layer->bottom_shapes.resize(layer->bottoms.size());
  2255. for (size_t j = 0; j < layer->bottoms.size(); j++)
  2256. {
  2257. int bottom_blob_index = layer->bottoms[j];
  2258. layer->bottom_shapes[j] = blobs[bottom_blob_index].shape;
  2259. }
  2260. layer->top_shapes.resize(layer->tops.size());
  2261. for (size_t j = 0; j < layer->tops.size(); j++)
  2262. {
  2263. int top_blob_index = layer->tops[j];
  2264. layer->top_shapes[j] = blobs[top_blob_index].shape;
  2265. // fprintf(stderr, "%d %4d %4d %4d | %2d %s\n", blobs[top_blob_index].shape.dims, blobs[top_blob_index].shape.w, blobs[top_blob_index].shape.h, blobs[top_blob_index].shape.c, top_blob_index, blobs[top_blob_index].name.c_str());
  2266. }
  2267. }
  2268. return 0;
  2269. }
  2270. int NetOptimize::estimate_memory_footprint()
  2271. {
  2272. if (has_custom_layer)
  2273. {
  2274. fprintf(stderr, "model has custom layer, estimate_memory_footprint skipped\n");
  2275. return -1;
  2276. }
  2277. const size_t layer_count = layers.size();
  2278. const size_t blob_count = blobs.size();
  2279. MemoryFootprintAllocator allocator;
  2280. ncnn::Extractor ex = create_extractor();
  2281. ex.set_blob_allocator(&allocator);
  2282. ex.set_workspace_allocator(&allocator);
  2283. // prepare Input blobs
  2284. for (size_t i = 0; i < layer_count; i++)
  2285. {
  2286. const ncnn::Layer* layer = layers[i];
  2287. if (layer->type == "ncnnfused")
  2288. continue;
  2289. if (layer->type != "Input")
  2290. continue;
  2291. ncnn::Input* input = (ncnn::Input*)layer;
  2292. int w = input->w;
  2293. int h = input->h;
  2294. int c = input->c;
  2295. int dims = 0;
  2296. if (w == 0 && h == 0 && c == 0) dims = 0;
  2297. if (w != 0 && h == 0 && c == 0) dims = 1;
  2298. if (w != 0 && h != 0 && c == 0) dims = 2;
  2299. if (w != 0 && h != 0 && c != 0) dims = 3;
  2300. if (dims == 0)
  2301. {
  2302. fprintf(stderr, "Input layer %s without shape info, estimate_memory_footprint skipped\n", layer->name.c_str());
  2303. return -1;
  2304. }
  2305. ncnn::Mat m;
  2306. if (dims == 1) m.create(w, 4u, &allocator);
  2307. if (dims == 2) m.create(w, h, 4u, &allocator);
  2308. if (dims == 3) m.create(w, h, c, 4u, &allocator);
  2309. ex.input(layer->tops[0], m);
  2310. fprintf(stderr, "input = %s\n", blobs[layer->tops[0]].name.c_str());
  2311. }
  2312. // find output blobs and do inference
  2313. std::vector<ncnn::Mat> outputs;
  2314. for (size_t i = 0; i < blob_count; i++)
  2315. {
  2316. const ncnn::Blob& blob = blobs[i];
  2317. if (blob.producer == -1 || blob.consumer != -1)
  2318. continue;
  2319. // treat blob without any consumers as output
  2320. ncnn::Mat m;
  2321. ex.extract(int(i), m);
  2322. outputs.push_back(m);
  2323. fprintf(stderr, "extract = %s\n", blob.name.c_str());
  2324. }
  2325. fprintf(stderr, "estimated memory footprint = %.2f KB = %.2f MB\n", allocator.memory_footprint / 1024.f, allocator.memory_footprint / 1024.f / 1024.f);
  2326. return 0;
  2327. }
  2328. int NetOptimize::set_cutparam(const char* cutstartname, const char* cutendname)
  2329. {
  2330. if (cutstartname != nullptr)
  2331. {
  2332. int layindex = find_layer_index_by_name(cutstartname);
  2333. if (layindex >= 0)
  2334. {
  2335. cutstart = layindex;
  2336. fprintf(stderr, "cutstart layer %d:%s\n", layindex, cutstartname);
  2337. }
  2338. else
  2339. {
  2340. fprintf(stderr, "not find target cutstart layer %s\n", cutstartname);
  2341. return -1;
  2342. }
  2343. }
  2344. if (cutendname != nullptr)
  2345. {
  2346. int layindex = find_layer_index_by_name(cutendname);
  2347. if (layindex >= 0)
  2348. {
  2349. cutend = layindex;
  2350. fprintf(stderr, "cutend layer %d:%s\n", layindex, cutendname);
  2351. }
  2352. else
  2353. {
  2354. fprintf(stderr, "not find target cutend layer %s\n", cutendname);
  2355. return -1;
  2356. }
  2357. }
  2358. return 0;
  2359. }
  2360. int NetOptimize::fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp)
  2361. {
  2362. const int count = m.w;
  2363. const int* ptr = m;
  2364. fprintf(pp, " -%d=%d", 23300 + id, count);
  2365. for (int i = 0; i < count; i++)
  2366. {
  2367. fprintf(pp, ",%d", ptr[i]);
  2368. }
  2369. return 0;
  2370. }
  2371. int NetOptimize::fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp)
  2372. {
  2373. const int count = m.w;
  2374. const float* ptr = m;
  2375. fprintf(pp, " -%d=%d", 23300 + id, count);
  2376. for (int i = 0; i < count; i++)
  2377. {
  2378. fprintf(pp, ",%e", ptr[i]);
  2379. }
  2380. return 0;
  2381. }
  2382. static inline size_t alignSize(size_t sz, int n)
  2383. {
  2384. return (sz + n - 1) & -n;
  2385. }
  2386. int NetOptimize::fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp)
  2387. {
  2388. int p0 = ftell(bp);
  2389. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  2390. if (storage_type == 1 && tag == 0)
  2391. {
  2392. tag = 0x01306B47; // fp16 magic
  2393. fwrite(&tag, sizeof(int), 1, bp);
  2394. ncnn::Mat data_flattened_fp16;
  2395. ncnn::cast_float32_to_float16(data_flattened, data_flattened_fp16);
  2396. fwrite(data_flattened_fp16.data, data_flattened_fp16.elemsize, data_flattened_fp16.w, bp);
  2397. }
  2398. else
  2399. {
  2400. fwrite(&tag, sizeof(int), 1, bp);
  2401. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  2402. }
  2403. // padding to 32bit align
  2404. int nwrite = ftell(bp) - p0;
  2405. size_t nalign = alignSize(nwrite, 4);
  2406. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  2407. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  2408. return 0;
  2409. }
  2410. int NetOptimize::fwrite_weight_data(const ncnn::Mat& data, FILE* bp)
  2411. {
  2412. int p0 = ftell(bp);
  2413. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  2414. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  2415. // padding to 32bit align
  2416. int nwrite = ftell(bp) - p0;
  2417. size_t nalign = alignSize(nwrite, 4);
  2418. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  2419. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  2420. return 0;
  2421. }
  2422. int NetOptimize::save(const char* parampath, const char* binpath)
  2423. {
  2424. unsigned int mac = 0;
  2425. FILE* pp = fopen(parampath, "wb");
  2426. FILE* bp = fopen(binpath, "wb");
  2427. fprintf(pp, "7767517\n");
  2428. const size_t layer_count = layers.size();
  2429. int layer_count_fused = 0;
  2430. std::set<std::string> blob_names;
  2431. for (size_t i = 0; i < layer_count; i++)
  2432. {
  2433. const ncnn::Layer* layer = layers[i];
  2434. if (layer->type == "ncnnfused")
  2435. continue;
  2436. layer_count_fused++;
  2437. size_t bottom_count = layer->bottoms.size();
  2438. for (size_t j = 0; j < bottom_count; j++)
  2439. {
  2440. int bottom_blob_index = layer->bottoms[j];
  2441. blob_names.insert(blobs[bottom_blob_index].name);
  2442. }
  2443. size_t top_count = layer->tops.size();
  2444. for (size_t j = 0; j < top_count; j++)
  2445. {
  2446. int top_blob_index = layer->tops[j];
  2447. blob_names.insert(blobs[top_blob_index].name);
  2448. }
  2449. }
  2450. size_t blob_count_fused = blob_names.size();
  2451. fprintf(pp, "%d %zd\n", layer_count_fused, blob_count_fused);
  2452. for (size_t i = 0; i < layer_count; i++)
  2453. {
  2454. const ncnn::Layer* layer = layers[i];
  2455. if (layer->type == "ncnnfused")
  2456. continue;
  2457. if (cutstart > 0 && i < cutstart)
  2458. continue;
  2459. if (cutend > 0 && i > cutend)
  2460. continue;
  2461. size_t bottom_count = layer->bottoms.size();
  2462. size_t top_count = layer->tops.size();
  2463. fprintf(pp, "%-24s %-24s %zd %zd", layer->type.c_str(), layer->name.c_str(), bottom_count, top_count);
  2464. for (size_t j = 0; j < bottom_count; j++)
  2465. {
  2466. int bottom_blob_index = layer->bottoms[j];
  2467. fprintf(pp, " %s", blobs[bottom_blob_index].name.c_str());
  2468. }
  2469. for (size_t j = 0; j < top_count; j++)
  2470. {
  2471. int top_blob_index = layer->tops[j];
  2472. fprintf(pp, " %s", blobs[top_blob_index].name.c_str());
  2473. }
  2474. // write shape hints
  2475. bool shape_ready = true;
  2476. for (size_t j = 0; j < top_count; j++)
  2477. {
  2478. int top_blob_index = layer->tops[j];
  2479. int dims = blobs[top_blob_index].shape.dims;
  2480. if (dims == 0)
  2481. {
  2482. shape_ready = false;
  2483. break;
  2484. }
  2485. }
  2486. if (shape_ready)
  2487. {
  2488. fprintf(pp, " -23330=%zd", top_count * 4);
  2489. for (size_t j = 0; j < top_count; j++)
  2490. {
  2491. int top_blob_index = layer->tops[j];
  2492. int dims = blobs[top_blob_index].shape.dims;
  2493. int w = blobs[top_blob_index].shape.w;
  2494. int h = blobs[top_blob_index].shape.h;
  2495. int c = blobs[top_blob_index].shape.c;
  2496. fprintf(pp, ",%d,%d,%d,%d", dims, w, h, c);
  2497. }
  2498. }
  2499. // custom op
  2500. if (layer->typeindex & ncnn::LayerType::CustomBit)
  2501. {
  2502. ((CustomLayer*)layer)->write_param(pp);
  2503. fprintf(pp, "\n");
  2504. continue;
  2505. }
  2506. ncnn::Layer* layer_default = ncnn::create_layer(layer->typeindex);
  2507. ncnn::ParamDict pd;
  2508. layer_default->load_param(pd);
  2509. #define fprintf_param_value(format, phase) \
  2510. { \
  2511. if (op->phase != op_default->phase) fprintf(pp, format, op->phase); \
  2512. }
  2513. if (layer->type == "BatchNorm")
  2514. {
  2515. ncnn::BatchNorm* op = (ncnn::BatchNorm*)layer;
  2516. ncnn::BatchNorm* op_default = (ncnn::BatchNorm*)layer_default;
  2517. fprintf_param_value(" 0=%d", channels)
  2518. fprintf_param_value(" 1=%e", eps)
  2519. fwrite_weight_data(op->slope_data, bp);
  2520. fwrite_weight_data(op->mean_data, bp);
  2521. fwrite_weight_data(op->var_data, bp);
  2522. fwrite_weight_data(op->bias_data, bp);
  2523. }
  2524. else if (layer->type == "Bias")
  2525. {
  2526. ncnn::Bias* op = (ncnn::Bias*)layer;
  2527. ncnn::Bias* op_default = (ncnn::Bias*)layer_default;
  2528. fprintf_param_value(" 0=%d", bias_data_size)
  2529. fwrite_weight_data(op->bias_data, bp);
  2530. }
  2531. else if (layer->type == "BinaryOp")
  2532. {
  2533. ncnn::BinaryOp* op = (ncnn::BinaryOp*)layer;
  2534. ncnn::BinaryOp* op_default = (ncnn::BinaryOp*)layer_default;
  2535. fprintf_param_value(" 0=%d", op_type)
  2536. fprintf_param_value(" 1=%d", with_scalar)
  2537. fprintf_param_value(" 2=%e", b)
  2538. }
  2539. else if (layer->type == "Clip")
  2540. {
  2541. ncnn::Clip* op = (ncnn::Clip*)layer;
  2542. ncnn::Clip* op_default = (ncnn::Clip*)layer_default;
  2543. fprintf_param_value(" 0=%e", min)
  2544. fprintf_param_value(" 1=%e", max)
  2545. }
  2546. else if (layer->type == "Concat")
  2547. {
  2548. ncnn::Concat* op = (ncnn::Concat*)layer;
  2549. ncnn::Concat* op_default = (ncnn::Concat*)layer_default;
  2550. fprintf_param_value(" 0=%d", axis)
  2551. }
  2552. else if (layer->type == "Convolution")
  2553. {
  2554. ncnn::Convolution* op = (ncnn::Convolution*)layer;
  2555. ncnn::Convolution* op_default = (ncnn::Convolution*)layer_default;
  2556. fprintf_param_value(" 0=%d", num_output)
  2557. fprintf_param_value(" 1=%d", kernel_w)
  2558. {
  2559. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2560. }
  2561. fprintf_param_value(" 2=%d", dilation_w)
  2562. {
  2563. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2564. }
  2565. fprintf_param_value(" 3=%d", stride_w)
  2566. {
  2567. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2568. }
  2569. fprintf_param_value(" 4=%d", pad_left)
  2570. {
  2571. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2572. }
  2573. {
  2574. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2575. }
  2576. {
  2577. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2578. }
  2579. fprintf_param_value(" 18=%e", pad_value)
  2580. fprintf_param_value(" 5=%d", bias_term)
  2581. fprintf_param_value(" 6=%d", weight_data_size)
  2582. fprintf_param_value(" 8=%d", int8_scale_term)
  2583. fprintf_param_value(" 9=%d", activation_type)
  2584. {
  2585. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2586. }
  2587. fprintf_param_value(" 17=%d", impl_type)
  2588. fwrite_weight_tag_data(0, op->weight_data, bp);
  2589. fwrite_weight_data(op->bias_data, bp);
  2590. if (shape_ready)
  2591. {
  2592. int inc = blobs[layer->bottoms[0]].shape.c;
  2593. int outw = blobs[layer->tops[0]].shape.w;
  2594. int outh = blobs[layer->tops[0]].shape.h;
  2595. int outc = blobs[layer->tops[0]].shape.c;
  2596. mac += op->kernel_h * op->kernel_w * outw * outh * outc * inc;
  2597. }
  2598. }
  2599. else if (layer->type == "ConvolutionDepthWise")
  2600. {
  2601. ncnn::ConvolutionDepthWise* op = (ncnn::ConvolutionDepthWise*)layer;
  2602. ncnn::ConvolutionDepthWise* op_default = (ncnn::ConvolutionDepthWise*)layer_default;
  2603. fprintf_param_value(" 0=%d", num_output)
  2604. fprintf_param_value(" 1=%d", kernel_w)
  2605. {
  2606. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2607. }
  2608. fprintf_param_value(" 2=%d", dilation_w)
  2609. {
  2610. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2611. }
  2612. fprintf_param_value(" 3=%d", stride_w)
  2613. {
  2614. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2615. }
  2616. fprintf_param_value(" 4=%d", pad_left)
  2617. {
  2618. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2619. }
  2620. {
  2621. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2622. }
  2623. {
  2624. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2625. }
  2626. fprintf_param_value(" 18=%e", pad_value)
  2627. fprintf_param_value(" 5=%d", bias_term)
  2628. fprintf_param_value(" 6=%d", weight_data_size)
  2629. fprintf_param_value(" 7=%d", group)
  2630. fprintf_param_value(" 8=%d", int8_scale_term)
  2631. fprintf_param_value(" 9=%d", activation_type)
  2632. {
  2633. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2634. }
  2635. fwrite_weight_tag_data(0, op->weight_data, bp);
  2636. fwrite_weight_data(op->bias_data, bp);
  2637. if (shape_ready)
  2638. {
  2639. int inc = blobs[layer->bottoms[0]].shape.c;
  2640. int outw = blobs[layer->tops[0]].shape.w;
  2641. int outh = blobs[layer->tops[0]].shape.h;
  2642. int outc = blobs[layer->tops[0]].shape.c;
  2643. mac += op->kernel_h * op->kernel_w * outw * outh * (outc / op->group) * (inc / op->group) * op->group;
  2644. }
  2645. }
  2646. else if (layer->type == "Crop")
  2647. {
  2648. ncnn::Crop* op = (ncnn::Crop*)layer;
  2649. ncnn::Crop* op_default = (ncnn::Crop*)layer_default;
  2650. fprintf_param_value(" 0=%d", woffset)
  2651. fprintf_param_value(" 1=%d", hoffset)
  2652. fprintf_param_value(" 2=%d", coffset)
  2653. fprintf_param_value(" 3=%d", outw)
  2654. fprintf_param_value(" 4=%d", outh)
  2655. fprintf_param_value(" 5=%d", outc)
  2656. fprintf_param_value(" 6=%d", woffset2)
  2657. fprintf_param_value(" 7=%d", hoffset2)
  2658. fprintf_param_value(" 8=%d", coffset2)
  2659. {
  2660. if (!op->starts.empty()) fprintf_param_int_array(9, op->starts, pp);
  2661. }
  2662. {
  2663. if (!op->ends.empty()) fprintf_param_int_array(10, op->ends, pp);
  2664. }
  2665. {
  2666. if (!op->axes.empty()) fprintf_param_int_array(11, op->axes, pp);
  2667. }
  2668. }
  2669. else if (layer->type == "Deconvolution")
  2670. {
  2671. ncnn::Deconvolution* op = (ncnn::Deconvolution*)layer;
  2672. ncnn::Deconvolution* op_default = (ncnn::Deconvolution*)layer_default;
  2673. fprintf_param_value(" 0=%d", num_output)
  2674. fprintf_param_value(" 1=%d", kernel_w)
  2675. {
  2676. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2677. }
  2678. fprintf_param_value(" 2=%d", dilation_w)
  2679. {
  2680. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2681. }
  2682. fprintf_param_value(" 3=%d", stride_w)
  2683. {
  2684. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2685. }
  2686. fprintf_param_value(" 4=%d", pad_left)
  2687. {
  2688. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2689. }
  2690. {
  2691. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2692. }
  2693. {
  2694. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2695. }
  2696. fprintf_param_value(" 18=%d", output_pad_right)
  2697. {
  2698. if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom);
  2699. }
  2700. fprintf_param_value(" 20=%d", output_w)
  2701. {
  2702. if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h);
  2703. }
  2704. fprintf_param_value(" 5=%d", bias_term)
  2705. fprintf_param_value(" 6=%d", weight_data_size)
  2706. fprintf_param_value(" 9=%d", activation_type)
  2707. {
  2708. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2709. }
  2710. fwrite_weight_tag_data(0, op->weight_data, bp);
  2711. fwrite_weight_data(op->bias_data, bp);
  2712. if (shape_ready)
  2713. {
  2714. int inw = blobs[layer->bottoms[0]].shape.w;
  2715. int inh = blobs[layer->bottoms[0]].shape.h;
  2716. int inc = blobs[layer->bottoms[0]].shape.c;
  2717. int outc = blobs[layer->tops[0]].shape.c;
  2718. mac += op->kernel_h * op->kernel_w * inw * inh * outc * inc;
  2719. }
  2720. }
  2721. else if (layer->type == "DeconvolutionDepthWise")
  2722. {
  2723. ncnn::DeconvolutionDepthWise* op = (ncnn::DeconvolutionDepthWise*)layer;
  2724. ncnn::DeconvolutionDepthWise* op_default = (ncnn::DeconvolutionDepthWise*)layer_default;
  2725. fprintf_param_value(" 0=%d", num_output)
  2726. fprintf_param_value(" 1=%d", kernel_w)
  2727. {
  2728. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2729. }
  2730. fprintf_param_value(" 2=%d", dilation_w)
  2731. {
  2732. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2733. }
  2734. fprintf_param_value(" 3=%d", stride_w)
  2735. {
  2736. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2737. }
  2738. fprintf_param_value(" 4=%d", pad_left)
  2739. {
  2740. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2741. }
  2742. {
  2743. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2744. }
  2745. {
  2746. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2747. }
  2748. fprintf_param_value(" 18=%d", output_pad_right)
  2749. {
  2750. if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom);
  2751. }
  2752. fprintf_param_value(" 20=%d", output_w)
  2753. {
  2754. if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h);
  2755. }
  2756. fprintf_param_value(" 5=%d", bias_term)
  2757. fprintf_param_value(" 6=%d", weight_data_size)
  2758. fprintf_param_value(" 7=%d", group)
  2759. fprintf_param_value(" 9=%d", activation_type)
  2760. {
  2761. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2762. }
  2763. fwrite_weight_tag_data(0, op->weight_data, bp);
  2764. fwrite_weight_data(op->bias_data, bp);
  2765. if (shape_ready)
  2766. {
  2767. int inw = blobs[layer->bottoms[0]].shape.w;
  2768. int inh = blobs[layer->bottoms[0]].shape.h;
  2769. int inc = blobs[layer->bottoms[0]].shape.c;
  2770. int outc = blobs[layer->tops[0]].shape.c;
  2771. mac += op->kernel_h * op->kernel_w * inw * inh * (outc / op->group) * (inc / op->group) * op->group;
  2772. }
  2773. }
  2774. else if (layer->type == "DetectionOutput")
  2775. {
  2776. ncnn::DetectionOutput* op = (ncnn::DetectionOutput*)layer;
  2777. ncnn::DetectionOutput* op_default = (ncnn::DetectionOutput*)layer_default;
  2778. fprintf_param_value(" 0=%d", num_class)
  2779. fprintf_param_value(" 1=%e", nms_threshold)
  2780. fprintf_param_value(" 2=%d", nms_top_k)
  2781. fprintf_param_value(" 3=%d", keep_top_k)
  2782. fprintf_param_value(" 4=%e", confidence_threshold)
  2783. fprintf_param_value(" 5=%e", variances[0])
  2784. fprintf_param_value(" 6=%e", variances[1])
  2785. fprintf_param_value(" 7=%e", variances[2])
  2786. fprintf_param_value(" 8=%e", variances[3])
  2787. }
  2788. else if (layer->type == "Dropout")
  2789. {
  2790. ncnn::Dropout* op = (ncnn::Dropout*)layer;
  2791. ncnn::Dropout* op_default = (ncnn::Dropout*)layer_default;
  2792. fprintf_param_value(" 0=%e", scale)
  2793. }
  2794. else if (layer->type == "Eltwise")
  2795. {
  2796. ncnn::Eltwise* op = (ncnn::Eltwise*)layer;
  2797. ncnn::Eltwise* op_default = (ncnn::Eltwise*)layer_default;
  2798. fprintf_param_value(" 0=%d", op_type)
  2799. {
  2800. if (!op->coeffs.empty()) fprintf_param_float_array(1, op->coeffs, pp);
  2801. }
  2802. }
  2803. else if (layer->type == "ELU")
  2804. {
  2805. ncnn::ELU* op = (ncnn::ELU*)layer;
  2806. ncnn::ELU* op_default = (ncnn::ELU*)layer_default;
  2807. fprintf_param_value(" 0=%e", alpha)
  2808. }
  2809. else if (layer->type == "Exp")
  2810. {
  2811. ncnn::Exp* op = (ncnn::Exp*)layer;
  2812. ncnn::Exp* op_default = (ncnn::Exp*)layer_default;
  2813. fprintf_param_value(" 0=%e", base)
  2814. fprintf_param_value(" 1=%e", scale)
  2815. fprintf_param_value(" 2=%e", shift)
  2816. }
  2817. else if (layer->type == "ExpandDims")
  2818. {
  2819. ncnn::ExpandDims* op = (ncnn::ExpandDims*)layer;
  2820. ncnn::ExpandDims* op_default = (ncnn::ExpandDims*)layer_default;
  2821. fprintf_param_value(" 0=%d", expand_w)
  2822. fprintf_param_value(" 1=%d", expand_h)
  2823. fprintf_param_value(" 2=%d", expand_c)
  2824. {
  2825. if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp);
  2826. }
  2827. }
  2828. else if (layer->type == "Gemm")
  2829. {
  2830. ncnn::Gemm* op = (ncnn::Gemm*)layer;
  2831. ncnn::Gemm* op_default = (ncnn::Gemm*)layer_default;
  2832. fprintf_param_value(" 0=%e", alpha)
  2833. fprintf_param_value(" 1=%e", beta)
  2834. fprintf_param_value(" 2=%d", transA)
  2835. fprintf_param_value(" 3=%d", transB)
  2836. }
  2837. else if (layer->type == "GroupNorm")
  2838. {
  2839. ncnn::GroupNorm* op = (ncnn::GroupNorm*)layer;
  2840. ncnn::GroupNorm* op_default = (ncnn::GroupNorm*)layer_default;
  2841. fprintf_param_value(" 0=%d", group)
  2842. fprintf_param_value(" 1=%d", channels)
  2843. fprintf_param_value(" 2=%e", eps)
  2844. fprintf_param_value(" 3=%d", affine)
  2845. fwrite_weight_data(op->gamma_data, bp);
  2846. fwrite_weight_data(op->beta_data, bp);
  2847. }
  2848. else if (layer->type == "GRU")
  2849. {
  2850. ncnn::GRU* op = (ncnn::GRU*)layer;
  2851. ncnn::GRU* op_default = (ncnn::GRU*)layer_default;
  2852. fprintf_param_value(" 0=%d", num_output)
  2853. fprintf_param_value(" 1=%d", weight_data_size)
  2854. fprintf_param_value(" 2=%d", direction)
  2855. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  2856. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  2857. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  2858. }
  2859. else if (layer->type == "HardSigmoid")
  2860. {
  2861. ncnn::HardSigmoid* op = (ncnn::HardSigmoid*)layer;
  2862. ncnn::HardSigmoid* op_default = (ncnn::HardSigmoid*)layer_default;
  2863. fprintf_param_value(" 0=%e", alpha)
  2864. fprintf_param_value(" 1=%e", beta)
  2865. }
  2866. else if (layer->type == "HardSwish")
  2867. {
  2868. ncnn::HardSwish* op = (ncnn::HardSwish*)layer;
  2869. ncnn::HardSwish* op_default = (ncnn::HardSwish*)layer_default;
  2870. fprintf_param_value(" 0=%e", alpha)
  2871. fprintf_param_value(" 1=%e", beta)
  2872. }
  2873. else if (layer->type == "InnerProduct")
  2874. {
  2875. ncnn::InnerProduct* op = (ncnn::InnerProduct*)layer;
  2876. ncnn::InnerProduct* op_default = (ncnn::InnerProduct*)layer_default;
  2877. fprintf_param_value(" 0=%d", num_output)
  2878. fprintf_param_value(" 1=%d", bias_term)
  2879. fprintf_param_value(" 2=%d", weight_data_size)
  2880. fprintf_param_value(" 8=%d", int8_scale_term)
  2881. fprintf_param_value(" 9=%d", activation_type)
  2882. {
  2883. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2884. }
  2885. fwrite_weight_tag_data(0, op->weight_data, bp);
  2886. fwrite_weight_data(op->bias_data, bp);
  2887. if (shape_ready)
  2888. {
  2889. int inw = blobs[layer->bottoms[0]].shape.w;
  2890. int inh = blobs[layer->bottoms[0]].shape.h;
  2891. int inc = blobs[layer->bottoms[0]].shape.c;
  2892. int outw = blobs[layer->tops[0]].shape.w;
  2893. mac += inw * inh * inc * outw;
  2894. }
  2895. }
  2896. else if (layer->type == "Input")
  2897. {
  2898. ncnn::Input* op = (ncnn::Input*)layer;
  2899. ncnn::Input* op_default = (ncnn::Input*)layer_default;
  2900. fprintf_param_value(" 0=%d", w)
  2901. fprintf_param_value(" 1=%d", h)
  2902. fprintf_param_value(" 2=%d", c)
  2903. }
  2904. else if (layer->type == "InstanceNorm")
  2905. {
  2906. ncnn::InstanceNorm* op = (ncnn::InstanceNorm*)layer;
  2907. ncnn::InstanceNorm* op_default = (ncnn::InstanceNorm*)layer_default;
  2908. fprintf_param_value(" 0=%d", channels)
  2909. fprintf_param_value(" 1=%e", eps)
  2910. fprintf_param_value(" 2=%d", affine)
  2911. fwrite_weight_data(op->gamma_data, bp);
  2912. fwrite_weight_data(op->beta_data, bp);
  2913. }
  2914. else if (layer->type == "Interp")
  2915. {
  2916. ncnn::Interp* op = (ncnn::Interp*)layer;
  2917. ncnn::Interp* op_default = (ncnn::Interp*)layer_default;
  2918. fprintf_param_value(" 0=%d", resize_type)
  2919. fprintf_param_value(" 1=%e", height_scale)
  2920. fprintf_param_value(" 2=%e", width_scale)
  2921. fprintf_param_value(" 3=%d", output_height)
  2922. fprintf_param_value(" 4=%d", output_width)
  2923. }
  2924. else if (layer->type == "Log")
  2925. {
  2926. ncnn::Log* op = (ncnn::Log*)layer;
  2927. ncnn::Log* op_default = (ncnn::Log*)layer_default;
  2928. fprintf_param_value(" 0=%e", base)
  2929. fprintf_param_value(" 1=%e", scale)
  2930. fprintf_param_value(" 2=%e", shift)
  2931. }
  2932. else if (layer->type == "LRN")
  2933. {
  2934. ncnn::LRN* op = (ncnn::LRN*)layer;
  2935. ncnn::LRN* op_default = (ncnn::LRN*)layer_default;
  2936. fprintf_param_value(" 0=%d", region_type)
  2937. fprintf_param_value(" 1=%d", local_size)
  2938. fprintf_param_value(" 2=%e", alpha)
  2939. fprintf_param_value(" 3=%e", beta)
  2940. fprintf_param_value(" 4=%e", bias)
  2941. }
  2942. else if (layer->type == "LSTM")
  2943. {
  2944. ncnn::LSTM* op = (ncnn::LSTM*)layer;
  2945. ncnn::LSTM* op_default = (ncnn::LSTM*)layer_default;
  2946. fprintf_param_value(" 0=%d", num_output)
  2947. fprintf_param_value(" 1=%d", weight_data_size)
  2948. fprintf_param_value(" 2=%d", direction)
  2949. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  2950. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  2951. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  2952. }
  2953. else if (layer->type == "MemoryData")
  2954. {
  2955. ncnn::MemoryData* op = (ncnn::MemoryData*)layer;
  2956. ncnn::MemoryData* op_default = (ncnn::MemoryData*)layer_default;
  2957. fprintf_param_value(" 0=%d", w)
  2958. fprintf_param_value(" 1=%d", h)
  2959. fprintf_param_value(" 2=%d", c)
  2960. fwrite_weight_data(op->data, bp);
  2961. }
  2962. else if (layer->type == "MVN")
  2963. {
  2964. ncnn::MVN* op = (ncnn::MVN*)layer;
  2965. ncnn::MVN* op_default = (ncnn::MVN*)layer_default;
  2966. fprintf_param_value(" 0=%d", normalize_variance)
  2967. fprintf_param_value(" 1=%d", across_channels)
  2968. fprintf_param_value(" 2=%e", eps)
  2969. }
  2970. else if (layer->type == "Normalize")
  2971. {
  2972. ncnn::Normalize* op = (ncnn::Normalize*)layer;
  2973. ncnn::Normalize* op_default = (ncnn::Normalize*)layer_default;
  2974. fprintf_param_value(" 0=%d", across_spatial)
  2975. fprintf_param_value(" 1=%d", channel_shared)
  2976. fprintf_param_value(" 2=%e", eps)
  2977. fprintf_param_value(" 3=%d", scale_data_size)
  2978. fprintf_param_value(" 4=%d", across_channel)
  2979. fprintf_param_value(" 9=%d", eps_mode)
  2980. fwrite_weight_data(op->scale_data, bp);
  2981. }
  2982. else if (layer->type == "Padding")
  2983. {
  2984. ncnn::Padding* op = (ncnn::Padding*)layer;
  2985. ncnn::Padding* op_default = (ncnn::Padding*)layer_default;
  2986. fprintf_param_value(" 0=%d", top)
  2987. fprintf_param_value(" 1=%d", bottom)
  2988. fprintf_param_value(" 2=%d", left)
  2989. fprintf_param_value(" 3=%d", right)
  2990. fprintf_param_value(" 4=%d", type)
  2991. fprintf_param_value(" 5=%e", value)
  2992. fprintf_param_value(" 6=%d", per_channel_pad_data_size)
  2993. fprintf_param_value(" 7=%d", front)
  2994. fprintf_param_value(" 8=%d", behind)
  2995. fwrite_weight_data(op->per_channel_pad_data, bp);
  2996. }
  2997. else if (layer->type == "Permute")
  2998. {
  2999. ncnn::Permute* op = (ncnn::Permute*)layer;
  3000. ncnn::Permute* op_default = (ncnn::Permute*)layer_default;
  3001. fprintf_param_value(" 0=%d", order_type)
  3002. }
  3003. else if (layer->type == "PixelShuffle")
  3004. {
  3005. ncnn::PixelShuffle* op = (ncnn::PixelShuffle*)layer;
  3006. ncnn::PixelShuffle* op_default = (ncnn::PixelShuffle*)layer_default;
  3007. fprintf_param_value(" 0=%d", upscale_factor)
  3008. fprintf_param_value(" 1=%d", mode)
  3009. }
  3010. else if (layer->type == "Pooling")
  3011. {
  3012. ncnn::Pooling* op = (ncnn::Pooling*)layer;
  3013. ncnn::Pooling* op_default = (ncnn::Pooling*)layer_default;
  3014. fprintf_param_value(" 0=%d", pooling_type)
  3015. fprintf_param_value(" 1=%d", kernel_w)
  3016. {
  3017. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  3018. }
  3019. fprintf_param_value(" 2=%d", stride_w)
  3020. {
  3021. if (op->stride_h != op->stride_w) fprintf(pp, " 12=%d", op->stride_h);
  3022. }
  3023. fprintf_param_value(" 3=%d", pad_left)
  3024. {
  3025. if (op->pad_top != op->pad_left) fprintf(pp, " 13=%d", op->pad_top);
  3026. }
  3027. {
  3028. if (op->pad_right != op->pad_left) fprintf(pp, " 14=%d", op->pad_right);
  3029. }
  3030. {
  3031. if (op->pad_bottom != op->pad_top) fprintf(pp, " 15=%d", op->pad_bottom);
  3032. }
  3033. fprintf_param_value(" 4=%d", global_pooling)
  3034. fprintf_param_value(" 5=%d", pad_mode)
  3035. fprintf_param_value(" 6=%d", avgpool_count_include_pad)
  3036. fprintf_param_value(" 7=%d", adaptive_pooling)
  3037. fprintf_param_value(" 8=%d", out_w)
  3038. {
  3039. if (op->out_h != op->out_w) fprintf(pp, " 18=%d", op->out_h);
  3040. }
  3041. }
  3042. else if (layer->type == "Power")
  3043. {
  3044. ncnn::Power* op = (ncnn::Power*)layer;
  3045. ncnn::Power* op_default = (ncnn::Power*)layer_default;
  3046. fprintf_param_value(" 0=%e", power)
  3047. fprintf_param_value(" 1=%e", scale)
  3048. fprintf_param_value(" 2=%e", shift)
  3049. }
  3050. else if (layer->type == "PReLU")
  3051. {
  3052. ncnn::PReLU* op = (ncnn::PReLU*)layer;
  3053. ncnn::PReLU* op_default = (ncnn::PReLU*)layer_default;
  3054. fprintf_param_value(" 0=%d", num_slope)
  3055. fwrite_weight_data(op->slope_data, bp);
  3056. }
  3057. else if (layer->type == "PriorBox")
  3058. {
  3059. ncnn::PriorBox* op = (ncnn::PriorBox*)layer;
  3060. ncnn::PriorBox* op_default = (ncnn::PriorBox*)layer_default;
  3061. {
  3062. if (!op->min_sizes.empty()) fprintf_param_float_array(0, op->min_sizes, pp);
  3063. }
  3064. {
  3065. if (!op->max_sizes.empty()) fprintf_param_float_array(1, op->max_sizes, pp);
  3066. }
  3067. {
  3068. if (!op->aspect_ratios.empty()) fprintf_param_float_array(2, op->aspect_ratios, pp);
  3069. }
  3070. fprintf_param_value(" 3=%e", variances[0])
  3071. fprintf_param_value(" 4=%e", variances[1])
  3072. fprintf_param_value(" 5=%e", variances[2])
  3073. fprintf_param_value(" 6=%e", variances[3])
  3074. fprintf_param_value(" 7=%d", flip)
  3075. fprintf_param_value(" 8=%d", clip)
  3076. fprintf_param_value(" 9=%d", image_width)
  3077. fprintf_param_value(" 10=%d", image_height)
  3078. fprintf_param_value(" 11=%e", step_width)
  3079. fprintf_param_value(" 12=%e", step_height)
  3080. fprintf_param_value(" 13=%e", offset)
  3081. }
  3082. else if (layer->type == "Proposal")
  3083. {
  3084. ncnn::Proposal* op = (ncnn::Proposal*)layer;
  3085. ncnn::Proposal* op_default = (ncnn::Proposal*)layer_default;
  3086. fprintf_param_value(" 0=%d", feat_stride)
  3087. fprintf_param_value(" 1=%d", base_size)
  3088. fprintf_param_value(" 2=%d", pre_nms_topN)
  3089. fprintf_param_value(" 3=%d", after_nms_topN)
  3090. fprintf_param_value(" 4=%e", nms_thresh)
  3091. fprintf_param_value(" 5=%d", min_size)
  3092. }
  3093. else if (layer->type == "PSROIPooling")
  3094. {
  3095. ncnn::PSROIPooling* op = (ncnn::PSROIPooling*)layer;
  3096. ncnn::PSROIPooling* op_default = (ncnn::PSROIPooling*)layer_default;
  3097. fprintf_param_value(" 0=%d", pooled_width)
  3098. fprintf_param_value(" 1=%d", pooled_height)
  3099. fprintf_param_value(" 2=%e", spatial_scale)
  3100. fprintf_param_value(" 3=%d", output_dim)
  3101. }
  3102. else if (layer->type == "Quantize")
  3103. {
  3104. ncnn::Quantize* op = (ncnn::Quantize*)layer;
  3105. ncnn::Quantize* op_default = (ncnn::Quantize*)layer_default;
  3106. fprintf_param_value(" 0=%e", scale)
  3107. }
  3108. else if (layer->type == "Reduction")
  3109. {
  3110. ncnn::Reduction* op = (ncnn::Reduction*)layer;
  3111. ncnn::Reduction* op_default = (ncnn::Reduction*)layer_default;
  3112. fprintf_param_value(" 0=%d", operation)
  3113. fprintf_param_value(" 1=%d", reduce_all)
  3114. fprintf_param_value(" 2=%e", coeff)
  3115. {
  3116. if (!op->axes.empty()) fprintf_param_int_array(3, op->axes, pp);
  3117. }
  3118. fprintf_param_value(" 4=%d", keepdims)
  3119. }
  3120. else if (layer->type == "ReLU")
  3121. {
  3122. ncnn::ReLU* op = (ncnn::ReLU*)layer;
  3123. ncnn::ReLU* op_default = (ncnn::ReLU*)layer_default;
  3124. fprintf_param_value(" 0=%e", slope)
  3125. }
  3126. else if (layer->type == "Reorg")
  3127. {
  3128. ncnn::Reorg* op = (ncnn::Reorg*)layer;
  3129. ncnn::Reorg* op_default = (ncnn::Reorg*)layer_default;
  3130. fprintf_param_value(" 0=%d", stride)
  3131. fprintf_param_value(" 1=%d", mode)
  3132. }
  3133. else if (layer->type == "Requantize")
  3134. {
  3135. ncnn::Requantize* op = (ncnn::Requantize*)layer;
  3136. ncnn::Requantize* op_default = (ncnn::Requantize*)layer_default;
  3137. fprintf_param_value(" 0=%e", scale_in)
  3138. fprintf_param_value(" 1=%e", scale_out)
  3139. fprintf_param_value(" 2=%d", bias_term)
  3140. fprintf_param_value(" 3=%d", bias_data_size)
  3141. fprintf_param_value(" 4=%d", fusion_relu)
  3142. }
  3143. else if (layer->type == "Reshape")
  3144. {
  3145. ncnn::Reshape* op = (ncnn::Reshape*)layer;
  3146. ncnn::Reshape* op_default = (ncnn::Reshape*)layer_default;
  3147. fprintf_param_value(" 0=%d", w)
  3148. fprintf_param_value(" 1=%d", h)
  3149. fprintf_param_value(" 2=%d", c)
  3150. fprintf_param_value(" 3=%d", permute)
  3151. }
  3152. else if (layer->type == "RNN")
  3153. {
  3154. ncnn::RNN* op = (ncnn::RNN*)layer;
  3155. ncnn::RNN* op_default = (ncnn::RNN*)layer_default;
  3156. fprintf_param_value(" 0=%d", num_output)
  3157. fprintf_param_value(" 1=%d", weight_data_size)
  3158. fprintf_param_value(" 2=%d", direction)
  3159. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  3160. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  3161. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  3162. }
  3163. else if (layer->type == "ROIAlign")
  3164. {
  3165. ncnn::ROIAlign* op = (ncnn::ROIAlign*)layer;
  3166. ncnn::ROIAlign* op_default = (ncnn::ROIAlign*)layer_default;
  3167. fprintf_param_value(" 0=%d", pooled_width)
  3168. fprintf_param_value(" 1=%d", pooled_height)
  3169. fprintf_param_value(" 2=%e", spatial_scale)
  3170. fprintf_param_value(" 3=%d", sampling_ratio)
  3171. fprintf_param_value(" 4=%d", aligned)
  3172. fprintf_param_value(" 5=%d", version)
  3173. }
  3174. else if (layer->type == "ROIPooling")
  3175. {
  3176. ncnn::ROIPooling* op = (ncnn::ROIPooling*)layer;
  3177. ncnn::ROIPooling* op_default = (ncnn::ROIPooling*)layer_default;
  3178. fprintf_param_value(" 0=%d", pooled_width)
  3179. fprintf_param_value(" 1=%d", pooled_height)
  3180. fprintf_param_value(" 2=%e", spatial_scale)
  3181. }
  3182. else if (layer->type == "Scale")
  3183. {
  3184. ncnn::Scale* op = (ncnn::Scale*)layer;
  3185. ncnn::Scale* op_default = (ncnn::Scale*)layer_default;
  3186. fprintf_param_value(" 0=%d", scale_data_size)
  3187. fprintf_param_value(" 1=%d", bias_term)
  3188. fwrite_weight_data(op->scale_data, bp);
  3189. fwrite_weight_data(op->bias_data, bp);
  3190. }
  3191. else if (layer->type == "ShuffleChannel")
  3192. {
  3193. ncnn::ShuffleChannel* op = (ncnn::ShuffleChannel*)layer;
  3194. ncnn::ShuffleChannel* op_default = (ncnn::ShuffleChannel*)layer_default;
  3195. fprintf_param_value(" 0=%d", group)
  3196. fprintf_param_value(" 1=%d", reverse)
  3197. }
  3198. else if (layer->type == "Slice")
  3199. {
  3200. ncnn::Slice* op = (ncnn::Slice*)layer;
  3201. ncnn::Slice* op_default = (ncnn::Slice*)layer_default;
  3202. {
  3203. if (!op->slices.empty()) fprintf_param_int_array(0, op->slices, pp);
  3204. }
  3205. fprintf_param_value(" 1=%d", axis)
  3206. }
  3207. else if (layer->type == "Softmax")
  3208. {
  3209. ncnn::Softmax* op = (ncnn::Softmax*)layer;
  3210. ncnn::Softmax* op_default = (ncnn::Softmax*)layer_default;
  3211. fprintf_param_value(" 0=%d", axis)
  3212. // HACK
  3213. if (op->axis != 0)
  3214. {
  3215. int fixbug0 = 1;
  3216. fprintf(pp, " 1=%d", fixbug0);
  3217. }
  3218. }
  3219. else if (layer->type == "Squeeze")
  3220. {
  3221. ncnn::Squeeze* op = (ncnn::Squeeze*)layer;
  3222. ncnn::Squeeze* op_default = (ncnn::Squeeze*)layer_default;
  3223. fprintf_param_value(" 0=%d", squeeze_w)
  3224. fprintf_param_value(" 1=%d", squeeze_h)
  3225. fprintf_param_value(" 2=%d", squeeze_c)
  3226. {
  3227. if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp);
  3228. }
  3229. }
  3230. else if (layer->type == "Threshold")
  3231. {
  3232. ncnn::Threshold* op = (ncnn::Threshold*)layer;
  3233. ncnn::Threshold* op_default = (ncnn::Threshold*)layer_default;
  3234. fprintf_param_value(" 0=%e", threshold)
  3235. }
  3236. else if (layer->type == "UnaryOp")
  3237. {
  3238. ncnn::UnaryOp* op = (ncnn::UnaryOp*)layer;
  3239. ncnn::UnaryOp* op_default = (ncnn::UnaryOp*)layer_default;
  3240. fprintf_param_value(" 0=%d", op_type)
  3241. }
  3242. else if (layer->type == "YoloDetectionOutput")
  3243. {
  3244. ncnn::YoloDetectionOutput* op = (ncnn::YoloDetectionOutput*)layer;
  3245. ncnn::YoloDetectionOutput* op_default = (ncnn::YoloDetectionOutput*)layer_default;
  3246. fprintf_param_value(" 0=%d", num_class)
  3247. fprintf_param_value(" 1=%d", num_box)
  3248. fprintf_param_value(" 2=%e", confidence_threshold)
  3249. fprintf_param_value(" 3=%e", nms_threshold)
  3250. {
  3251. if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp);
  3252. }
  3253. }
  3254. else if (layer->type == "Yolov3DetectionOutput")
  3255. {
  3256. ncnn::Yolov3DetectionOutput* op = (ncnn::Yolov3DetectionOutput*)layer;
  3257. ncnn::Yolov3DetectionOutput* op_default = (ncnn::Yolov3DetectionOutput*)layer_default;
  3258. fprintf_param_value(" 0=%d", num_class)
  3259. fprintf_param_value(" 1=%d", num_box)
  3260. fprintf_param_value(" 2=%e", confidence_threshold)
  3261. fprintf_param_value(" 3=%e", nms_threshold)
  3262. {
  3263. if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp);
  3264. }
  3265. {
  3266. if (!op->mask.empty()) fprintf_param_int_array(5, op->mask, pp);
  3267. }
  3268. {
  3269. if (!op->anchors_scale.empty()) fprintf_param_float_array(6, op->anchors_scale, pp);
  3270. }
  3271. }
  3272. #undef fprintf_param_value
  3273. fprintf(pp, "\n");
  3274. delete layer_default;
  3275. }
  3276. fclose(pp);
  3277. fclose(bp);
  3278. if (mac)
  3279. {
  3280. fprintf(stderr, "mac = %d = %.2f M\n", mac, mac / 1000000.f);
  3281. }
  3282. return 0;
  3283. }
  3284. int main(int argc, char** argv)
  3285. {
  3286. if (argc < 6)
  3287. {
  3288. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag] [cutstart] [cutend]\n", argv[0]);
  3289. return -1;
  3290. }
  3291. const char* inparam = argv[1];
  3292. const char* inbin = argv[2];
  3293. const char* outparam = argv[3];
  3294. const char* outbin = argv[4];
  3295. int flag = atoi(argv[5]);
  3296. const char* cutstartname = nullptr;
  3297. const char* cutendname = nullptr;
  3298. if (argc > 6)
  3299. {
  3300. cutstartname = argv[6];
  3301. }
  3302. if (argc > 7)
  3303. {
  3304. cutendname = argv[7];
  3305. }
  3306. NetOptimize optimizer;
  3307. if (flag == 65536 || flag == 1)
  3308. {
  3309. optimizer.storage_type = 1;
  3310. }
  3311. else
  3312. {
  3313. optimizer.storage_type = 0;
  3314. }
  3315. optimizer.load_param(inparam);
  3316. if (strcmp(inbin, "null") == 0)
  3317. {
  3318. DataReaderFromEmpty dr;
  3319. optimizer.load_model(dr);
  3320. }
  3321. else
  3322. optimizer.load_model(inbin);
  3323. if (optimizer.set_cutparam(cutstartname, cutendname) < 0)
  3324. {
  3325. return -1;
  3326. }
  3327. optimizer.fuse_batchnorm_scale();
  3328. optimizer.fuse_convolution_batchnorm();
  3329. optimizer.fuse_convolution_mul();
  3330. optimizer.fuse_convolution_add();
  3331. optimizer.fuse_convolutiondepthwise_batchnorm();
  3332. optimizer.fuse_convolutiondepthwise_mul();
  3333. optimizer.fuse_convolutiondepthwise_add();
  3334. optimizer.fuse_deconvolution_batchnorm();
  3335. optimizer.fuse_deconvolution_mul();
  3336. optimizer.fuse_deconvolution_add();
  3337. optimizer.fuse_deconvolutiondepthwise_batchnorm();
  3338. optimizer.fuse_innerproduct_batchnorm();
  3339. optimizer.fuse_innerproduct_add();
  3340. optimizer.fuse_innerproduct_dropout();
  3341. optimizer.replace_reduction_with_global_pooling();
  3342. optimizer.replace_prelu_with_leaky_relu();
  3343. optimizer.fuse_convolution_activation();
  3344. optimizer.fuse_convolutiondepthwise_activation();
  3345. optimizer.fuse_deconvolution_activation();
  3346. optimizer.fuse_deconvolutiondepthwise_activation();
  3347. optimizer.fuse_innerproduct_activation();
  3348. optimizer.fuse_memorydata_binaryop();
  3349. optimizer.fuse_binaryop_eltwise();
  3350. optimizer.eliminate_dropout();
  3351. optimizer.eliminate_pooling1x1();
  3352. optimizer.eliminate_noop();
  3353. optimizer.eliminate_flatten_after_global_pooling();
  3354. optimizer.eliminate_reshape_after_global_pooling();
  3355. optimizer.eliminate_reshape_before_binaryop();
  3356. optimizer.replace_convolution_with_innerproduct_after_global_pooling();
  3357. optimizer.replace_convolution_with_innerproduct_after_innerproduct();
  3358. optimizer.eliminate_flatten_after_innerproduct();
  3359. optimizer.eliminate_orphaned_memorydata();
  3360. optimizer.shape_inference();
  3361. optimizer.estimate_memory_footprint();
  3362. optimizer.save(outparam, outbin);
  3363. return 0;
  3364. }