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

ncnnoptimize.cpp 130 kB

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