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