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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170
  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. #if NCNN_INT8
  2130. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  2131. innerproduct->bottom_blob_int8_scales = convolution->bottom_blob_int8_scales;
  2132. #endif
  2133. innerproduct->activation_type = convolution->activation_type;
  2134. innerproduct->activation_params = convolution->activation_params;
  2135. layers[j] = innerproduct;
  2136. delete convolution;
  2137. }
  2138. return 0;
  2139. }
  2140. int NetOptimize::replace_convolution_with_innerproduct_after_innerproduct()
  2141. {
  2142. const size_t layer_count = layers.size();
  2143. for (;;)
  2144. {
  2145. bool replaced = false;
  2146. for (size_t i = 0; i < layer_count; i++)
  2147. {
  2148. if (layers[i]->type != "InnerProduct")
  2149. continue;
  2150. // InnerProduct - Convolution
  2151. int top_blob_index = layers[i]->tops[0];
  2152. size_t j = i + 1;
  2153. for (; j < layer_count; j++)
  2154. {
  2155. if (layers[j]->type != "Convolution")
  2156. continue;
  2157. if (layers[j]->bottoms.size() != 1)
  2158. continue;
  2159. if (layers[j]->bottoms[0] == top_blob_index)
  2160. break;
  2161. }
  2162. if (j == layer_count)
  2163. continue;
  2164. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  2165. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  2166. fprintf(stderr, "replace_convolution_with_innerproduct_after_innerproduct %s %s\n", innerproduct->name.c_str(), convolution->name.c_str());
  2167. ncnn::InnerProduct* innerproduct2 = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  2168. innerproduct2->type = "InnerProduct";
  2169. innerproduct2->name = convolution->name;
  2170. innerproduct2->bottoms = convolution->bottoms;
  2171. innerproduct2->tops = convolution->tops;
  2172. ncnn::ParamDict pd;
  2173. innerproduct2->load_param(pd);
  2174. innerproduct2->num_output = convolution->num_output;
  2175. innerproduct2->bias_term = convolution->bias_term;
  2176. innerproduct2->weight_data_size = convolution->weight_data_size;
  2177. innerproduct->int8_scale_term = convolution->int8_scale_term;
  2178. innerproduct2->weight_data = convolution->weight_data;
  2179. innerproduct2->bias_data = convolution->bias_data;
  2180. #if NCNN_INT8
  2181. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  2182. innerproduct->bottom_blob_int8_scales = convolution->bottom_blob_int8_scales;
  2183. #endif
  2184. innerproduct2->activation_type = convolution->activation_type;
  2185. innerproduct2->activation_params = convolution->activation_params;
  2186. layers[j] = innerproduct2;
  2187. delete convolution;
  2188. replaced = true;
  2189. }
  2190. if (!replaced)
  2191. break;
  2192. }
  2193. return 0;
  2194. }
  2195. int NetOptimize::shape_inference()
  2196. {
  2197. if (has_custom_layer)
  2198. {
  2199. fprintf(stderr, "model has custom layer, shape_inference skipped\n");
  2200. return -1;
  2201. }
  2202. const size_t layer_count = layers.size();
  2203. const size_t blob_count = blobs.size();
  2204. ncnn::Extractor ex = create_extractor();
  2205. // prepare Input blobs
  2206. for (size_t i = 0; i < layer_count; i++)
  2207. {
  2208. const ncnn::Layer* layer = layers[i];
  2209. if (layer->type == "ncnnfused")
  2210. continue;
  2211. if (layer->type != "Input")
  2212. continue;
  2213. ncnn::Input* input = (ncnn::Input*)layer;
  2214. int w = input->w;
  2215. int h = input->h;
  2216. int c = input->c;
  2217. int dims = 0;
  2218. if (w == 0 && h == 0 && c == 0) dims = 0;
  2219. if (w != 0 && h == 0 && c == 0) dims = 1;
  2220. if (w != 0 && h != 0 && c == 0) dims = 2;
  2221. if (w != 0 && h != 0 && c != 0) dims = 3;
  2222. if (dims == 0)
  2223. {
  2224. fprintf(stderr, "Input layer %s without shape info, shape_inference skipped\n", layer->name.c_str());
  2225. return -1;
  2226. }
  2227. ncnn::Mat m;
  2228. if (dims == 1) m.create(w);
  2229. if (dims == 2) m.create(w, h);
  2230. if (dims == 3) m.create(w, h, c);
  2231. ex.input(layer->tops[0], m);
  2232. }
  2233. // prepare blobs with predefined shape
  2234. for (size_t i = 0; i < blob_count; i++)
  2235. {
  2236. const ncnn::Blob& blob = blobs[i];
  2237. int dims = blob.shape.dims;
  2238. int w = blob.shape.w;
  2239. int h = blob.shape.h;
  2240. int c = blob.shape.c;
  2241. if (dims == 0)
  2242. continue;
  2243. ncnn::Mat m;
  2244. if (dims == 1) m.create(w);
  2245. if (dims == 2) m.create(w, h);
  2246. if (dims == 3) m.create(w, h, c);
  2247. ex.input(int(i), m);
  2248. }
  2249. fprintf(stderr, "shape_inference\n");
  2250. // resolve all layer output blob shape
  2251. for (size_t i = 0; i < layer_count; i++)
  2252. {
  2253. const ncnn::Layer* layer = layers[i];
  2254. if (layer->type == "ncnnfused")
  2255. continue;
  2256. for (size_t j = 0; j < layer->tops.size(); j++)
  2257. {
  2258. int top_blob_index = layer->tops[j];
  2259. ncnn::Mat m;
  2260. ex.extract(top_blob_index, m);
  2261. blobs[top_blob_index].shape = m;
  2262. }
  2263. }
  2264. // assign all layer blob shape
  2265. for (size_t i = 0; i < layer_count; i++)
  2266. {
  2267. ncnn::Layer* layer = layers[i];
  2268. if (layer->type == "ncnnfused")
  2269. continue;
  2270. layer->bottom_shapes.resize(layer->bottoms.size());
  2271. for (size_t j = 0; j < layer->bottoms.size(); j++)
  2272. {
  2273. int bottom_blob_index = layer->bottoms[j];
  2274. layer->bottom_shapes[j] = blobs[bottom_blob_index].shape;
  2275. }
  2276. layer->top_shapes.resize(layer->tops.size());
  2277. for (size_t j = 0; j < layer->tops.size(); j++)
  2278. {
  2279. int top_blob_index = layer->tops[j];
  2280. layer->top_shapes[j] = blobs[top_blob_index].shape;
  2281. // fprintf(stderr, "%d %4d %4d %4d | %2d %s\n", blobs[top_blob_index].shape.dims, blobs[top_blob_index].shape.w, blobs[top_blob_index].shape.h, blobs[top_blob_index].shape.c, top_blob_index, blobs[top_blob_index].name.c_str());
  2282. }
  2283. }
  2284. return 0;
  2285. }
  2286. int NetOptimize::estimate_memory_footprint()
  2287. {
  2288. if (has_custom_layer)
  2289. {
  2290. fprintf(stderr, "model has custom layer, estimate_memory_footprint skipped\n");
  2291. return -1;
  2292. }
  2293. const size_t layer_count = layers.size();
  2294. const size_t blob_count = blobs.size();
  2295. MemoryFootprintAllocator allocator;
  2296. ncnn::Extractor ex = create_extractor();
  2297. ex.set_blob_allocator(&allocator);
  2298. ex.set_workspace_allocator(&allocator);
  2299. // prepare Input blobs
  2300. for (size_t i = 0; i < layer_count; i++)
  2301. {
  2302. const ncnn::Layer* layer = layers[i];
  2303. if (layer->type == "ncnnfused")
  2304. continue;
  2305. if (layer->type != "Input")
  2306. continue;
  2307. ncnn::Input* input = (ncnn::Input*)layer;
  2308. int w = input->w;
  2309. int h = input->h;
  2310. int c = input->c;
  2311. int dims = 0;
  2312. if (w == 0 && h == 0 && c == 0) dims = 0;
  2313. if (w != 0 && h == 0 && c == 0) dims = 1;
  2314. if (w != 0 && h != 0 && c == 0) dims = 2;
  2315. if (w != 0 && h != 0 && c != 0) dims = 3;
  2316. if (dims == 0)
  2317. {
  2318. fprintf(stderr, "Input layer %s without shape info, estimate_memory_footprint skipped\n", layer->name.c_str());
  2319. return -1;
  2320. }
  2321. ncnn::Mat m;
  2322. if (dims == 1) m.create(w, 4u, &allocator);
  2323. if (dims == 2) m.create(w, h, 4u, &allocator);
  2324. if (dims == 3) m.create(w, h, c, 4u, &allocator);
  2325. ex.input(layer->tops[0], m);
  2326. fprintf(stderr, "input = %s\n", blobs[layer->tops[0]].name.c_str());
  2327. }
  2328. // find output blobs and do inference
  2329. std::vector<ncnn::Mat> outputs;
  2330. for (size_t i = 0; i < blob_count; i++)
  2331. {
  2332. const ncnn::Blob& blob = blobs[i];
  2333. if (blob.producer == -1 || blob.consumer != -1)
  2334. continue;
  2335. // treat blob without any consumers as output
  2336. ncnn::Mat m;
  2337. ex.extract(int(i), m);
  2338. outputs.push_back(m);
  2339. fprintf(stderr, "extract = %s\n", blob.name.c_str());
  2340. }
  2341. fprintf(stderr, "estimated memory footprint = %.2f KB = %.2f MB\n", allocator.memory_footprint / 1024.f, allocator.memory_footprint / 1024.f / 1024.f);
  2342. return 0;
  2343. }
  2344. int NetOptimize::set_cutparam(const char* cutstartname, const char* cutendname)
  2345. {
  2346. if (cutstartname != nullptr)
  2347. {
  2348. int layindex = find_layer_index_by_name(cutstartname);
  2349. if (layindex >= 0)
  2350. {
  2351. cutstart = layindex;
  2352. fprintf(stderr, "cutstart layer %d:%s\n", layindex, cutstartname);
  2353. }
  2354. else
  2355. {
  2356. fprintf(stderr, "not find target cutstart layer %s\n", cutstartname);
  2357. return -1;
  2358. }
  2359. }
  2360. if (cutendname != nullptr)
  2361. {
  2362. int layindex = find_layer_index_by_name(cutendname);
  2363. if (layindex >= 0)
  2364. {
  2365. cutend = layindex;
  2366. fprintf(stderr, "cutend layer %d:%s\n", layindex, cutendname);
  2367. }
  2368. else
  2369. {
  2370. fprintf(stderr, "not find target cutend layer %s\n", cutendname);
  2371. return -1;
  2372. }
  2373. }
  2374. return 0;
  2375. }
  2376. int NetOptimize::fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp)
  2377. {
  2378. const int count = m.w;
  2379. const int* ptr = m;
  2380. fprintf(pp, " -%d=%d", 23300 + id, count);
  2381. for (int i = 0; i < count; i++)
  2382. {
  2383. fprintf(pp, ",%d", ptr[i]);
  2384. }
  2385. return 0;
  2386. }
  2387. int NetOptimize::fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp)
  2388. {
  2389. const int count = m.w;
  2390. const float* ptr = m;
  2391. fprintf(pp, " -%d=%d", 23300 + id, count);
  2392. for (int i = 0; i < count; i++)
  2393. {
  2394. fprintf(pp, ",%e", ptr[i]);
  2395. }
  2396. return 0;
  2397. }
  2398. static inline size_t alignSize(size_t sz, int n)
  2399. {
  2400. return (sz + n - 1) & -n;
  2401. }
  2402. int NetOptimize::fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp)
  2403. {
  2404. int p0 = ftell(bp);
  2405. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  2406. if (storage_type == 1 && tag == 0)
  2407. {
  2408. tag = 0x01306B47; // fp16 magic
  2409. fwrite(&tag, sizeof(int), 1, bp);
  2410. ncnn::Mat data_flattened_fp16;
  2411. ncnn::cast_float32_to_float16(data_flattened, data_flattened_fp16);
  2412. fwrite(data_flattened_fp16.data, data_flattened_fp16.elemsize, data_flattened_fp16.w, bp);
  2413. }
  2414. else
  2415. {
  2416. fwrite(&tag, sizeof(int), 1, bp);
  2417. if (data_flattened.elemsize == 4) // fp32
  2418. {
  2419. replace_denormals_with_zero(data_flattened, data_flattened.w);
  2420. }
  2421. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  2422. }
  2423. // padding to 32bit align
  2424. int nwrite = ftell(bp) - p0;
  2425. size_t nalign = alignSize(nwrite, 4);
  2426. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  2427. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  2428. return 0;
  2429. }
  2430. int NetOptimize::fwrite_weight_data(const ncnn::Mat& data, FILE* bp)
  2431. {
  2432. int p0 = ftell(bp);
  2433. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  2434. if (data_flattened.elemsize == 4) // fp32
  2435. {
  2436. replace_denormals_with_zero(data_flattened, data_flattened.w);
  2437. }
  2438. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  2439. // padding to 32bit align
  2440. int nwrite = ftell(bp) - p0;
  2441. size_t nalign = alignSize(nwrite, 4);
  2442. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  2443. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  2444. return 0;
  2445. }
  2446. int NetOptimize::save(const char* parampath, const char* binpath)
  2447. {
  2448. unsigned int mac = 0;
  2449. FILE* pp = fopen(parampath, "wb");
  2450. FILE* bp = fopen(binpath, "wb");
  2451. fprintf(pp, "7767517\n");
  2452. const size_t layer_count = layers.size();
  2453. int layer_count_fused = 0;
  2454. std::set<std::string> blob_names;
  2455. for (size_t i = 0; i < layer_count; i++)
  2456. {
  2457. const ncnn::Layer* layer = layers[i];
  2458. if (layer->type == "ncnnfused")
  2459. continue;
  2460. layer_count_fused++;
  2461. size_t bottom_count = layer->bottoms.size();
  2462. for (size_t j = 0; j < bottom_count; j++)
  2463. {
  2464. int bottom_blob_index = layer->bottoms[j];
  2465. blob_names.insert(blobs[bottom_blob_index].name);
  2466. }
  2467. size_t top_count = layer->tops.size();
  2468. for (size_t j = 0; j < top_count; j++)
  2469. {
  2470. int top_blob_index = layer->tops[j];
  2471. blob_names.insert(blobs[top_blob_index].name);
  2472. }
  2473. }
  2474. size_t blob_count_fused = blob_names.size();
  2475. fprintf(pp, "%d %zd\n", layer_count_fused, blob_count_fused);
  2476. for (size_t i = 0; i < layer_count; i++)
  2477. {
  2478. const ncnn::Layer* layer = layers[i];
  2479. if (layer->type == "ncnnfused")
  2480. continue;
  2481. if (cutstart > 0 && i < cutstart)
  2482. continue;
  2483. if (cutend > 0 && i > cutend)
  2484. continue;
  2485. size_t bottom_count = layer->bottoms.size();
  2486. size_t top_count = layer->tops.size();
  2487. fprintf(pp, "%-24s %-24s %zd %zd", layer->type.c_str(), layer->name.c_str(), bottom_count, top_count);
  2488. for (size_t j = 0; j < bottom_count; j++)
  2489. {
  2490. int bottom_blob_index = layer->bottoms[j];
  2491. fprintf(pp, " %s", blobs[bottom_blob_index].name.c_str());
  2492. }
  2493. for (size_t j = 0; j < top_count; j++)
  2494. {
  2495. int top_blob_index = layer->tops[j];
  2496. fprintf(pp, " %s", blobs[top_blob_index].name.c_str());
  2497. }
  2498. // write shape hints
  2499. bool shape_ready = true;
  2500. for (size_t j = 0; j < top_count; j++)
  2501. {
  2502. int top_blob_index = layer->tops[j];
  2503. int dims = blobs[top_blob_index].shape.dims;
  2504. if (dims == 0)
  2505. {
  2506. shape_ready = false;
  2507. break;
  2508. }
  2509. }
  2510. if (shape_ready)
  2511. {
  2512. fprintf(pp, " -23330=%zd", top_count * 4);
  2513. for (size_t j = 0; j < top_count; j++)
  2514. {
  2515. int top_blob_index = layer->tops[j];
  2516. int dims = blobs[top_blob_index].shape.dims;
  2517. int w = blobs[top_blob_index].shape.w;
  2518. int h = blobs[top_blob_index].shape.h;
  2519. int c = blobs[top_blob_index].shape.c;
  2520. fprintf(pp, ",%d,%d,%d,%d", dims, w, h, c);
  2521. }
  2522. }
  2523. // custom op
  2524. if (layer->typeindex & ncnn::LayerType::CustomBit)
  2525. {
  2526. ((CustomLayer*)layer)->write_param(pp);
  2527. fprintf(pp, "\n");
  2528. continue;
  2529. }
  2530. ncnn::Layer* layer_default = ncnn::create_layer(layer->typeindex);
  2531. ncnn::ParamDict pd;
  2532. layer_default->load_param(pd);
  2533. #define fprintf_param_value(format, phase) \
  2534. { \
  2535. if (op->phase != op_default->phase) fprintf(pp, format, op->phase); \
  2536. }
  2537. if (layer->type == "BatchNorm")
  2538. {
  2539. ncnn::BatchNorm* op = (ncnn::BatchNorm*)layer;
  2540. ncnn::BatchNorm* op_default = (ncnn::BatchNorm*)layer_default;
  2541. fprintf_param_value(" 0=%d", channels)
  2542. fprintf_param_value(" 1=%e", eps)
  2543. fwrite_weight_data(op->slope_data, bp);
  2544. fwrite_weight_data(op->mean_data, bp);
  2545. fwrite_weight_data(op->var_data, bp);
  2546. fwrite_weight_data(op->bias_data, bp);
  2547. }
  2548. else if (layer->type == "Bias")
  2549. {
  2550. ncnn::Bias* op = (ncnn::Bias*)layer;
  2551. ncnn::Bias* op_default = (ncnn::Bias*)layer_default;
  2552. fprintf_param_value(" 0=%d", bias_data_size)
  2553. fwrite_weight_data(op->bias_data, bp);
  2554. }
  2555. else if (layer->type == "BinaryOp")
  2556. {
  2557. ncnn::BinaryOp* op = (ncnn::BinaryOp*)layer;
  2558. ncnn::BinaryOp* op_default = (ncnn::BinaryOp*)layer_default;
  2559. fprintf_param_value(" 0=%d", op_type)
  2560. fprintf_param_value(" 1=%d", with_scalar)
  2561. fprintf_param_value(" 2=%e", b)
  2562. }
  2563. else if (layer->type == "Clip")
  2564. {
  2565. ncnn::Clip* op = (ncnn::Clip*)layer;
  2566. ncnn::Clip* op_default = (ncnn::Clip*)layer_default;
  2567. fprintf_param_value(" 0=%e", min)
  2568. fprintf_param_value(" 1=%e", max)
  2569. }
  2570. else if (layer->type == "Concat")
  2571. {
  2572. ncnn::Concat* op = (ncnn::Concat*)layer;
  2573. ncnn::Concat* op_default = (ncnn::Concat*)layer_default;
  2574. fprintf_param_value(" 0=%d", axis)
  2575. }
  2576. else if (layer->type == "Convolution")
  2577. {
  2578. ncnn::Convolution* op = (ncnn::Convolution*)layer;
  2579. ncnn::Convolution* op_default = (ncnn::Convolution*)layer_default;
  2580. fprintf_param_value(" 0=%d", num_output)
  2581. fprintf_param_value(" 1=%d", kernel_w)
  2582. {
  2583. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2584. }
  2585. fprintf_param_value(" 2=%d", dilation_w)
  2586. {
  2587. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2588. }
  2589. fprintf_param_value(" 3=%d", stride_w)
  2590. {
  2591. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2592. }
  2593. fprintf_param_value(" 4=%d", pad_left)
  2594. {
  2595. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2596. }
  2597. {
  2598. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2599. }
  2600. {
  2601. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2602. }
  2603. fprintf_param_value(" 18=%e", pad_value)
  2604. fprintf_param_value(" 5=%d", bias_term)
  2605. fprintf_param_value(" 6=%d", weight_data_size)
  2606. fprintf_param_value(" 8=%d", int8_scale_term)
  2607. fprintf_param_value(" 9=%d", activation_type)
  2608. {
  2609. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2610. }
  2611. fprintf_param_value(" 17=%d", impl_type)
  2612. fwrite_weight_tag_data(0, op->weight_data, bp);
  2613. fwrite_weight_data(op->bias_data, bp);
  2614. if (shape_ready)
  2615. {
  2616. int inc = blobs[layer->bottoms[0]].shape.c;
  2617. int outw = blobs[layer->tops[0]].shape.w;
  2618. int outh = blobs[layer->tops[0]].shape.h;
  2619. int outc = blobs[layer->tops[0]].shape.c;
  2620. mac += op->kernel_h * op->kernel_w * outw * outh * outc * inc;
  2621. }
  2622. }
  2623. else if (layer->type == "ConvolutionDepthWise")
  2624. {
  2625. ncnn::ConvolutionDepthWise* op = (ncnn::ConvolutionDepthWise*)layer;
  2626. ncnn::ConvolutionDepthWise* op_default = (ncnn::ConvolutionDepthWise*)layer_default;
  2627. fprintf_param_value(" 0=%d", num_output)
  2628. fprintf_param_value(" 1=%d", kernel_w)
  2629. {
  2630. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2631. }
  2632. fprintf_param_value(" 2=%d", dilation_w)
  2633. {
  2634. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2635. }
  2636. fprintf_param_value(" 3=%d", stride_w)
  2637. {
  2638. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2639. }
  2640. fprintf_param_value(" 4=%d", pad_left)
  2641. {
  2642. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2643. }
  2644. {
  2645. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2646. }
  2647. {
  2648. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2649. }
  2650. fprintf_param_value(" 18=%e", pad_value)
  2651. fprintf_param_value(" 5=%d", bias_term)
  2652. fprintf_param_value(" 6=%d", weight_data_size)
  2653. fprintf_param_value(" 7=%d", group)
  2654. fprintf_param_value(" 8=%d", int8_scale_term)
  2655. fprintf_param_value(" 9=%d", activation_type)
  2656. {
  2657. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2658. }
  2659. fwrite_weight_tag_data(0, op->weight_data, bp);
  2660. fwrite_weight_data(op->bias_data, bp);
  2661. if (shape_ready)
  2662. {
  2663. int inc = blobs[layer->bottoms[0]].shape.c;
  2664. int outw = blobs[layer->tops[0]].shape.w;
  2665. int outh = blobs[layer->tops[0]].shape.h;
  2666. int outc = blobs[layer->tops[0]].shape.c;
  2667. mac += op->kernel_h * op->kernel_w * outw * outh * (outc / op->group) * (inc / op->group) * op->group;
  2668. }
  2669. }
  2670. else if (layer->type == "Crop")
  2671. {
  2672. ncnn::Crop* op = (ncnn::Crop*)layer;
  2673. ncnn::Crop* op_default = (ncnn::Crop*)layer_default;
  2674. fprintf_param_value(" 0=%d", woffset)
  2675. fprintf_param_value(" 1=%d", hoffset)
  2676. fprintf_param_value(" 2=%d", coffset)
  2677. fprintf_param_value(" 3=%d", outw)
  2678. fprintf_param_value(" 4=%d", outh)
  2679. fprintf_param_value(" 5=%d", outc)
  2680. fprintf_param_value(" 6=%d", woffset2)
  2681. fprintf_param_value(" 7=%d", hoffset2)
  2682. fprintf_param_value(" 8=%d", coffset2)
  2683. {
  2684. if (!op->starts.empty()) fprintf_param_int_array(9, op->starts, pp);
  2685. }
  2686. {
  2687. if (!op->ends.empty()) fprintf_param_int_array(10, op->ends, pp);
  2688. }
  2689. {
  2690. if (!op->axes.empty()) fprintf_param_int_array(11, op->axes, pp);
  2691. }
  2692. }
  2693. else if (layer->type == "Deconvolution")
  2694. {
  2695. ncnn::Deconvolution* op = (ncnn::Deconvolution*)layer;
  2696. ncnn::Deconvolution* op_default = (ncnn::Deconvolution*)layer_default;
  2697. fprintf_param_value(" 0=%d", num_output)
  2698. fprintf_param_value(" 1=%d", kernel_w)
  2699. {
  2700. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2701. }
  2702. fprintf_param_value(" 2=%d", dilation_w)
  2703. {
  2704. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2705. }
  2706. fprintf_param_value(" 3=%d", stride_w)
  2707. {
  2708. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2709. }
  2710. fprintf_param_value(" 4=%d", pad_left)
  2711. {
  2712. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2713. }
  2714. {
  2715. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2716. }
  2717. {
  2718. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2719. }
  2720. fprintf_param_value(" 18=%d", output_pad_right)
  2721. {
  2722. if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom);
  2723. }
  2724. fprintf_param_value(" 20=%d", output_w)
  2725. {
  2726. if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h);
  2727. }
  2728. fprintf_param_value(" 5=%d", bias_term)
  2729. fprintf_param_value(" 6=%d", weight_data_size)
  2730. fprintf_param_value(" 9=%d", activation_type)
  2731. {
  2732. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2733. }
  2734. fwrite_weight_tag_data(0, op->weight_data, bp);
  2735. fwrite_weight_data(op->bias_data, bp);
  2736. if (shape_ready)
  2737. {
  2738. int inw = blobs[layer->bottoms[0]].shape.w;
  2739. int inh = blobs[layer->bottoms[0]].shape.h;
  2740. int inc = blobs[layer->bottoms[0]].shape.c;
  2741. int outc = blobs[layer->tops[0]].shape.c;
  2742. mac += op->kernel_h * op->kernel_w * inw * inh * outc * inc;
  2743. }
  2744. }
  2745. else if (layer->type == "DeconvolutionDepthWise")
  2746. {
  2747. ncnn::DeconvolutionDepthWise* op = (ncnn::DeconvolutionDepthWise*)layer;
  2748. ncnn::DeconvolutionDepthWise* op_default = (ncnn::DeconvolutionDepthWise*)layer_default;
  2749. fprintf_param_value(" 0=%d", num_output)
  2750. fprintf_param_value(" 1=%d", kernel_w)
  2751. {
  2752. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2753. }
  2754. fprintf_param_value(" 2=%d", dilation_w)
  2755. {
  2756. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2757. }
  2758. fprintf_param_value(" 3=%d", stride_w)
  2759. {
  2760. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2761. }
  2762. fprintf_param_value(" 4=%d", pad_left)
  2763. {
  2764. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2765. }
  2766. {
  2767. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2768. }
  2769. {
  2770. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2771. }
  2772. fprintf_param_value(" 18=%d", output_pad_right)
  2773. {
  2774. if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom);
  2775. }
  2776. fprintf_param_value(" 20=%d", output_w)
  2777. {
  2778. if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h);
  2779. }
  2780. fprintf_param_value(" 5=%d", bias_term)
  2781. fprintf_param_value(" 6=%d", weight_data_size)
  2782. fprintf_param_value(" 7=%d", group)
  2783. fprintf_param_value(" 9=%d", activation_type)
  2784. {
  2785. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2786. }
  2787. fwrite_weight_tag_data(0, op->weight_data, bp);
  2788. fwrite_weight_data(op->bias_data, bp);
  2789. if (shape_ready)
  2790. {
  2791. int inw = blobs[layer->bottoms[0]].shape.w;
  2792. int inh = blobs[layer->bottoms[0]].shape.h;
  2793. int inc = blobs[layer->bottoms[0]].shape.c;
  2794. int outc = blobs[layer->tops[0]].shape.c;
  2795. mac += op->kernel_h * op->kernel_w * inw * inh * (outc / op->group) * (inc / op->group) * op->group;
  2796. }
  2797. }
  2798. else if (layer->type == "DetectionOutput")
  2799. {
  2800. ncnn::DetectionOutput* op = (ncnn::DetectionOutput*)layer;
  2801. ncnn::DetectionOutput* op_default = (ncnn::DetectionOutput*)layer_default;
  2802. fprintf_param_value(" 0=%d", num_class)
  2803. fprintf_param_value(" 1=%e", nms_threshold)
  2804. fprintf_param_value(" 2=%d", nms_top_k)
  2805. fprintf_param_value(" 3=%d", keep_top_k)
  2806. fprintf_param_value(" 4=%e", confidence_threshold)
  2807. fprintf_param_value(" 5=%e", variances[0])
  2808. fprintf_param_value(" 6=%e", variances[1])
  2809. fprintf_param_value(" 7=%e", variances[2])
  2810. fprintf_param_value(" 8=%e", variances[3])
  2811. }
  2812. else if (layer->type == "Dropout")
  2813. {
  2814. ncnn::Dropout* op = (ncnn::Dropout*)layer;
  2815. ncnn::Dropout* op_default = (ncnn::Dropout*)layer_default;
  2816. fprintf_param_value(" 0=%e", scale)
  2817. }
  2818. else if (layer->type == "Eltwise")
  2819. {
  2820. ncnn::Eltwise* op = (ncnn::Eltwise*)layer;
  2821. ncnn::Eltwise* op_default = (ncnn::Eltwise*)layer_default;
  2822. fprintf_param_value(" 0=%d", op_type)
  2823. {
  2824. if (!op->coeffs.empty()) fprintf_param_float_array(1, op->coeffs, pp);
  2825. }
  2826. }
  2827. else if (layer->type == "ELU")
  2828. {
  2829. ncnn::ELU* op = (ncnn::ELU*)layer;
  2830. ncnn::ELU* op_default = (ncnn::ELU*)layer_default;
  2831. fprintf_param_value(" 0=%e", alpha)
  2832. }
  2833. else if (layer->type == "Exp")
  2834. {
  2835. ncnn::Exp* op = (ncnn::Exp*)layer;
  2836. ncnn::Exp* op_default = (ncnn::Exp*)layer_default;
  2837. fprintf_param_value(" 0=%e", base)
  2838. fprintf_param_value(" 1=%e", scale)
  2839. fprintf_param_value(" 2=%e", shift)
  2840. }
  2841. else if (layer->type == "ExpandDims")
  2842. {
  2843. ncnn::ExpandDims* op = (ncnn::ExpandDims*)layer;
  2844. ncnn::ExpandDims* op_default = (ncnn::ExpandDims*)layer_default;
  2845. fprintf_param_value(" 0=%d", expand_w)
  2846. fprintf_param_value(" 1=%d", expand_h)
  2847. fprintf_param_value(" 2=%d", expand_c)
  2848. {
  2849. if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp);
  2850. }
  2851. }
  2852. else if (layer->type == "Gemm")
  2853. {
  2854. ncnn::Gemm* op = (ncnn::Gemm*)layer;
  2855. ncnn::Gemm* op_default = (ncnn::Gemm*)layer_default;
  2856. fprintf_param_value(" 0=%e", alpha)
  2857. fprintf_param_value(" 1=%e", beta)
  2858. fprintf_param_value(" 2=%d", transA)
  2859. fprintf_param_value(" 3=%d", transB)
  2860. }
  2861. else if (layer->type == "GroupNorm")
  2862. {
  2863. ncnn::GroupNorm* op = (ncnn::GroupNorm*)layer;
  2864. ncnn::GroupNorm* op_default = (ncnn::GroupNorm*)layer_default;
  2865. fprintf_param_value(" 0=%d", group)
  2866. fprintf_param_value(" 1=%d", channels)
  2867. fprintf_param_value(" 2=%e", eps)
  2868. fprintf_param_value(" 3=%d", affine)
  2869. fwrite_weight_data(op->gamma_data, bp);
  2870. fwrite_weight_data(op->beta_data, bp);
  2871. }
  2872. else if (layer->type == "GRU")
  2873. {
  2874. ncnn::GRU* op = (ncnn::GRU*)layer;
  2875. ncnn::GRU* op_default = (ncnn::GRU*)layer_default;
  2876. fprintf_param_value(" 0=%d", num_output)
  2877. fprintf_param_value(" 1=%d", weight_data_size)
  2878. fprintf_param_value(" 2=%d", direction)
  2879. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  2880. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  2881. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  2882. }
  2883. else if (layer->type == "HardSigmoid")
  2884. {
  2885. ncnn::HardSigmoid* op = (ncnn::HardSigmoid*)layer;
  2886. ncnn::HardSigmoid* op_default = (ncnn::HardSigmoid*)layer_default;
  2887. fprintf_param_value(" 0=%e", alpha)
  2888. fprintf_param_value(" 1=%e", beta)
  2889. }
  2890. else if (layer->type == "HardSwish")
  2891. {
  2892. ncnn::HardSwish* op = (ncnn::HardSwish*)layer;
  2893. ncnn::HardSwish* op_default = (ncnn::HardSwish*)layer_default;
  2894. fprintf_param_value(" 0=%e", alpha)
  2895. fprintf_param_value(" 1=%e", beta)
  2896. }
  2897. else if (layer->type == "InnerProduct")
  2898. {
  2899. ncnn::InnerProduct* op = (ncnn::InnerProduct*)layer;
  2900. ncnn::InnerProduct* op_default = (ncnn::InnerProduct*)layer_default;
  2901. fprintf_param_value(" 0=%d", num_output)
  2902. fprintf_param_value(" 1=%d", bias_term)
  2903. fprintf_param_value(" 2=%d", weight_data_size)
  2904. fprintf_param_value(" 8=%d", int8_scale_term)
  2905. fprintf_param_value(" 9=%d", activation_type)
  2906. {
  2907. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2908. }
  2909. fwrite_weight_tag_data(0, op->weight_data, bp);
  2910. fwrite_weight_data(op->bias_data, bp);
  2911. if (shape_ready)
  2912. {
  2913. int inw = blobs[layer->bottoms[0]].shape.w;
  2914. int inh = blobs[layer->bottoms[0]].shape.h;
  2915. int inc = blobs[layer->bottoms[0]].shape.c;
  2916. int outw = blobs[layer->tops[0]].shape.w;
  2917. mac += inw * inh * inc * outw;
  2918. }
  2919. }
  2920. else if (layer->type == "Input")
  2921. {
  2922. ncnn::Input* op = (ncnn::Input*)layer;
  2923. ncnn::Input* op_default = (ncnn::Input*)layer_default;
  2924. fprintf_param_value(" 0=%d", w)
  2925. fprintf_param_value(" 1=%d", h)
  2926. fprintf_param_value(" 2=%d", c)
  2927. }
  2928. else if (layer->type == "InstanceNorm")
  2929. {
  2930. ncnn::InstanceNorm* op = (ncnn::InstanceNorm*)layer;
  2931. ncnn::InstanceNorm* op_default = (ncnn::InstanceNorm*)layer_default;
  2932. fprintf_param_value(" 0=%d", channels)
  2933. fprintf_param_value(" 1=%e", eps)
  2934. fprintf_param_value(" 2=%d", affine)
  2935. fwrite_weight_data(op->gamma_data, bp);
  2936. fwrite_weight_data(op->beta_data, bp);
  2937. }
  2938. else if (layer->type == "Interp")
  2939. {
  2940. ncnn::Interp* op = (ncnn::Interp*)layer;
  2941. ncnn::Interp* op_default = (ncnn::Interp*)layer_default;
  2942. fprintf_param_value(" 0=%d", resize_type)
  2943. fprintf_param_value(" 1=%e", height_scale)
  2944. fprintf_param_value(" 2=%e", width_scale)
  2945. fprintf_param_value(" 3=%d", output_height)
  2946. fprintf_param_value(" 4=%d", output_width)
  2947. }
  2948. else if (layer->type == "Log")
  2949. {
  2950. ncnn::Log* op = (ncnn::Log*)layer;
  2951. ncnn::Log* op_default = (ncnn::Log*)layer_default;
  2952. fprintf_param_value(" 0=%e", base)
  2953. fprintf_param_value(" 1=%e", scale)
  2954. fprintf_param_value(" 2=%e", shift)
  2955. }
  2956. else if (layer->type == "LRN")
  2957. {
  2958. ncnn::LRN* op = (ncnn::LRN*)layer;
  2959. ncnn::LRN* op_default = (ncnn::LRN*)layer_default;
  2960. fprintf_param_value(" 0=%d", region_type)
  2961. fprintf_param_value(" 1=%d", local_size)
  2962. fprintf_param_value(" 2=%e", alpha)
  2963. fprintf_param_value(" 3=%e", beta)
  2964. fprintf_param_value(" 4=%e", bias)
  2965. }
  2966. else if (layer->type == "LSTM")
  2967. {
  2968. ncnn::LSTM* op = (ncnn::LSTM*)layer;
  2969. ncnn::LSTM* op_default = (ncnn::LSTM*)layer_default;
  2970. fprintf_param_value(" 0=%d", num_output)
  2971. fprintf_param_value(" 1=%d", weight_data_size)
  2972. fprintf_param_value(" 2=%d", direction)
  2973. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  2974. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  2975. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  2976. }
  2977. else if (layer->type == "MemoryData")
  2978. {
  2979. ncnn::MemoryData* op = (ncnn::MemoryData*)layer;
  2980. ncnn::MemoryData* op_default = (ncnn::MemoryData*)layer_default;
  2981. fprintf_param_value(" 0=%d", w)
  2982. fprintf_param_value(" 1=%d", h)
  2983. fprintf_param_value(" 2=%d", c)
  2984. fwrite_weight_data(op->data, bp);
  2985. }
  2986. else if (layer->type == "MVN")
  2987. {
  2988. ncnn::MVN* op = (ncnn::MVN*)layer;
  2989. ncnn::MVN* op_default = (ncnn::MVN*)layer_default;
  2990. fprintf_param_value(" 0=%d", normalize_variance)
  2991. fprintf_param_value(" 1=%d", across_channels)
  2992. fprintf_param_value(" 2=%e", eps)
  2993. }
  2994. else if (layer->type == "Normalize")
  2995. {
  2996. ncnn::Normalize* op = (ncnn::Normalize*)layer;
  2997. ncnn::Normalize* op_default = (ncnn::Normalize*)layer_default;
  2998. fprintf_param_value(" 0=%d", across_spatial)
  2999. fprintf_param_value(" 1=%d", channel_shared)
  3000. fprintf_param_value(" 2=%e", eps)
  3001. fprintf_param_value(" 3=%d", scale_data_size)
  3002. fprintf_param_value(" 4=%d", across_channel)
  3003. fprintf_param_value(" 9=%d", eps_mode)
  3004. fwrite_weight_data(op->scale_data, bp);
  3005. }
  3006. else if (layer->type == "Padding")
  3007. {
  3008. ncnn::Padding* op = (ncnn::Padding*)layer;
  3009. ncnn::Padding* op_default = (ncnn::Padding*)layer_default;
  3010. fprintf_param_value(" 0=%d", top)
  3011. fprintf_param_value(" 1=%d", bottom)
  3012. fprintf_param_value(" 2=%d", left)
  3013. fprintf_param_value(" 3=%d", right)
  3014. fprintf_param_value(" 4=%d", type)
  3015. fprintf_param_value(" 5=%e", value)
  3016. fprintf_param_value(" 6=%d", per_channel_pad_data_size)
  3017. fprintf_param_value(" 7=%d", front)
  3018. fprintf_param_value(" 8=%d", behind)
  3019. fwrite_weight_data(op->per_channel_pad_data, bp);
  3020. }
  3021. else if (layer->type == "Permute")
  3022. {
  3023. ncnn::Permute* op = (ncnn::Permute*)layer;
  3024. ncnn::Permute* op_default = (ncnn::Permute*)layer_default;
  3025. fprintf_param_value(" 0=%d", order_type)
  3026. }
  3027. else if (layer->type == "PixelShuffle")
  3028. {
  3029. ncnn::PixelShuffle* op = (ncnn::PixelShuffle*)layer;
  3030. ncnn::PixelShuffle* op_default = (ncnn::PixelShuffle*)layer_default;
  3031. fprintf_param_value(" 0=%d", upscale_factor)
  3032. fprintf_param_value(" 1=%d", mode)
  3033. }
  3034. else if (layer->type == "Pooling")
  3035. {
  3036. ncnn::Pooling* op = (ncnn::Pooling*)layer;
  3037. ncnn::Pooling* op_default = (ncnn::Pooling*)layer_default;
  3038. fprintf_param_value(" 0=%d", pooling_type)
  3039. fprintf_param_value(" 1=%d", kernel_w)
  3040. {
  3041. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  3042. }
  3043. fprintf_param_value(" 2=%d", stride_w)
  3044. {
  3045. if (op->stride_h != op->stride_w) fprintf(pp, " 12=%d", op->stride_h);
  3046. }
  3047. fprintf_param_value(" 3=%d", pad_left)
  3048. {
  3049. if (op->pad_top != op->pad_left) fprintf(pp, " 13=%d", op->pad_top);
  3050. }
  3051. {
  3052. if (op->pad_right != op->pad_left) fprintf(pp, " 14=%d", op->pad_right);
  3053. }
  3054. {
  3055. if (op->pad_bottom != op->pad_top) fprintf(pp, " 15=%d", op->pad_bottom);
  3056. }
  3057. fprintf_param_value(" 4=%d", global_pooling)
  3058. fprintf_param_value(" 5=%d", pad_mode)
  3059. fprintf_param_value(" 6=%d", avgpool_count_include_pad)
  3060. fprintf_param_value(" 7=%d", adaptive_pooling)
  3061. fprintf_param_value(" 8=%d", out_w)
  3062. {
  3063. if (op->out_h != op->out_w) fprintf(pp, " 18=%d", op->out_h);
  3064. }
  3065. }
  3066. else if (layer->type == "Power")
  3067. {
  3068. ncnn::Power* op = (ncnn::Power*)layer;
  3069. ncnn::Power* op_default = (ncnn::Power*)layer_default;
  3070. fprintf_param_value(" 0=%e", power)
  3071. fprintf_param_value(" 1=%e", scale)
  3072. fprintf_param_value(" 2=%e", shift)
  3073. }
  3074. else if (layer->type == "PReLU")
  3075. {
  3076. ncnn::PReLU* op = (ncnn::PReLU*)layer;
  3077. ncnn::PReLU* op_default = (ncnn::PReLU*)layer_default;
  3078. fprintf_param_value(" 0=%d", num_slope)
  3079. fwrite_weight_data(op->slope_data, bp);
  3080. }
  3081. else if (layer->type == "PriorBox")
  3082. {
  3083. ncnn::PriorBox* op = (ncnn::PriorBox*)layer;
  3084. ncnn::PriorBox* op_default = (ncnn::PriorBox*)layer_default;
  3085. {
  3086. if (!op->min_sizes.empty()) fprintf_param_float_array(0, op->min_sizes, pp);
  3087. }
  3088. {
  3089. if (!op->max_sizes.empty()) fprintf_param_float_array(1, op->max_sizes, pp);
  3090. }
  3091. {
  3092. if (!op->aspect_ratios.empty()) fprintf_param_float_array(2, op->aspect_ratios, pp);
  3093. }
  3094. fprintf_param_value(" 3=%e", variances[0])
  3095. fprintf_param_value(" 4=%e", variances[1])
  3096. fprintf_param_value(" 5=%e", variances[2])
  3097. fprintf_param_value(" 6=%e", variances[3])
  3098. fprintf_param_value(" 7=%d", flip)
  3099. fprintf_param_value(" 8=%d", clip)
  3100. fprintf_param_value(" 9=%d", image_width)
  3101. fprintf_param_value(" 10=%d", image_height)
  3102. fprintf_param_value(" 11=%e", step_width)
  3103. fprintf_param_value(" 12=%e", step_height)
  3104. fprintf_param_value(" 13=%e", offset)
  3105. }
  3106. else if (layer->type == "Proposal")
  3107. {
  3108. ncnn::Proposal* op = (ncnn::Proposal*)layer;
  3109. ncnn::Proposal* op_default = (ncnn::Proposal*)layer_default;
  3110. fprintf_param_value(" 0=%d", feat_stride)
  3111. fprintf_param_value(" 1=%d", base_size)
  3112. fprintf_param_value(" 2=%d", pre_nms_topN)
  3113. fprintf_param_value(" 3=%d", after_nms_topN)
  3114. fprintf_param_value(" 4=%e", nms_thresh)
  3115. fprintf_param_value(" 5=%d", min_size)
  3116. }
  3117. else if (layer->type == "PSROIPooling")
  3118. {
  3119. ncnn::PSROIPooling* op = (ncnn::PSROIPooling*)layer;
  3120. ncnn::PSROIPooling* op_default = (ncnn::PSROIPooling*)layer_default;
  3121. fprintf_param_value(" 0=%d", pooled_width)
  3122. fprintf_param_value(" 1=%d", pooled_height)
  3123. fprintf_param_value(" 2=%e", spatial_scale)
  3124. fprintf_param_value(" 3=%d", output_dim)
  3125. }
  3126. else if (layer->type == "Quantize")
  3127. {
  3128. ncnn::Quantize* op = (ncnn::Quantize*)layer;
  3129. ncnn::Quantize* op_default = (ncnn::Quantize*)layer_default;
  3130. fprintf_param_value(" 0=%d", scale_data_size)
  3131. fwrite_weight_data(op->scale_data, bp);
  3132. }
  3133. else if (layer->type == "Reduction")
  3134. {
  3135. ncnn::Reduction* op = (ncnn::Reduction*)layer;
  3136. ncnn::Reduction* op_default = (ncnn::Reduction*)layer_default;
  3137. fprintf_param_value(" 0=%d", operation)
  3138. fprintf_param_value(" 1=%d", reduce_all)
  3139. fprintf_param_value(" 2=%e", coeff)
  3140. {
  3141. if (!op->axes.empty()) fprintf_param_int_array(3, op->axes, pp);
  3142. }
  3143. fprintf_param_value(" 4=%d", keepdims)
  3144. }
  3145. else if (layer->type == "ReLU")
  3146. {
  3147. ncnn::ReLU* op = (ncnn::ReLU*)layer;
  3148. ncnn::ReLU* op_default = (ncnn::ReLU*)layer_default;
  3149. fprintf_param_value(" 0=%e", slope)
  3150. }
  3151. else if (layer->type == "Reorg")
  3152. {
  3153. ncnn::Reorg* op = (ncnn::Reorg*)layer;
  3154. ncnn::Reorg* op_default = (ncnn::Reorg*)layer_default;
  3155. fprintf_param_value(" 0=%d", stride)
  3156. fprintf_param_value(" 1=%d", mode)
  3157. }
  3158. else if (layer->type == "Requantize")
  3159. {
  3160. ncnn::Requantize* op = (ncnn::Requantize*)layer;
  3161. ncnn::Requantize* op_default = (ncnn::Requantize*)layer_default;
  3162. fprintf_param_value(" 0=%d", scale_in_data_size)
  3163. fprintf_param_value(" 1=%d", scale_out_data_size)
  3164. fprintf_param_value(" 2=%d", bias_data_size)
  3165. fprintf_param_value(" 3=%d", activation_type)
  3166. {
  3167. if (!op->activation_params.empty()) fprintf_param_float_array(4, op->activation_params, pp);
  3168. }
  3169. fwrite_weight_data(op->scale_in_data, bp);
  3170. fwrite_weight_data(op->scale_out_data, bp);
  3171. fwrite_weight_data(op->bias_data, bp);
  3172. }
  3173. else if (layer->type == "Reshape")
  3174. {
  3175. ncnn::Reshape* op = (ncnn::Reshape*)layer;
  3176. ncnn::Reshape* op_default = (ncnn::Reshape*)layer_default;
  3177. fprintf_param_value(" 0=%d", w)
  3178. fprintf_param_value(" 1=%d", h)
  3179. fprintf_param_value(" 2=%d", c)
  3180. fprintf_param_value(" 3=%d", permute)
  3181. }
  3182. else if (layer->type == "RNN")
  3183. {
  3184. ncnn::RNN* op = (ncnn::RNN*)layer;
  3185. ncnn::RNN* op_default = (ncnn::RNN*)layer_default;
  3186. fprintf_param_value(" 0=%d", num_output)
  3187. fprintf_param_value(" 1=%d", weight_data_size)
  3188. fprintf_param_value(" 2=%d", direction)
  3189. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  3190. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  3191. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  3192. }
  3193. else if (layer->type == "ROIAlign")
  3194. {
  3195. ncnn::ROIAlign* op = (ncnn::ROIAlign*)layer;
  3196. ncnn::ROIAlign* op_default = (ncnn::ROIAlign*)layer_default;
  3197. fprintf_param_value(" 0=%d", pooled_width)
  3198. fprintf_param_value(" 1=%d", pooled_height)
  3199. fprintf_param_value(" 2=%e", spatial_scale)
  3200. fprintf_param_value(" 3=%d", sampling_ratio)
  3201. fprintf_param_value(" 4=%d", aligned)
  3202. fprintf_param_value(" 5=%d", version)
  3203. }
  3204. else if (layer->type == "ROIPooling")
  3205. {
  3206. ncnn::ROIPooling* op = (ncnn::ROIPooling*)layer;
  3207. ncnn::ROIPooling* op_default = (ncnn::ROIPooling*)layer_default;
  3208. fprintf_param_value(" 0=%d", pooled_width)
  3209. fprintf_param_value(" 1=%d", pooled_height)
  3210. fprintf_param_value(" 2=%e", spatial_scale)
  3211. }
  3212. else if (layer->type == "Scale")
  3213. {
  3214. ncnn::Scale* op = (ncnn::Scale*)layer;
  3215. ncnn::Scale* op_default = (ncnn::Scale*)layer_default;
  3216. fprintf_param_value(" 0=%d", scale_data_size)
  3217. fprintf_param_value(" 1=%d", bias_term)
  3218. fwrite_weight_data(op->scale_data, bp);
  3219. fwrite_weight_data(op->bias_data, bp);
  3220. }
  3221. else if (layer->type == "ShuffleChannel")
  3222. {
  3223. ncnn::ShuffleChannel* op = (ncnn::ShuffleChannel*)layer;
  3224. ncnn::ShuffleChannel* op_default = (ncnn::ShuffleChannel*)layer_default;
  3225. fprintf_param_value(" 0=%d", group)
  3226. fprintf_param_value(" 1=%d", reverse)
  3227. }
  3228. else if (layer->type == "Slice")
  3229. {
  3230. ncnn::Slice* op = (ncnn::Slice*)layer;
  3231. ncnn::Slice* op_default = (ncnn::Slice*)layer_default;
  3232. {
  3233. if (!op->slices.empty()) fprintf_param_int_array(0, op->slices, pp);
  3234. }
  3235. fprintf_param_value(" 1=%d", axis)
  3236. }
  3237. else if (layer->type == "Softmax")
  3238. {
  3239. ncnn::Softmax* op = (ncnn::Softmax*)layer;
  3240. ncnn::Softmax* op_default = (ncnn::Softmax*)layer_default;
  3241. fprintf_param_value(" 0=%d", axis)
  3242. // HACK
  3243. if (op->axis != 0)
  3244. {
  3245. int fixbug0 = 1;
  3246. fprintf(pp, " 1=%d", fixbug0);
  3247. }
  3248. }
  3249. else if (layer->type == "Squeeze")
  3250. {
  3251. ncnn::Squeeze* op = (ncnn::Squeeze*)layer;
  3252. ncnn::Squeeze* op_default = (ncnn::Squeeze*)layer_default;
  3253. fprintf_param_value(" 0=%d", squeeze_w)
  3254. fprintf_param_value(" 1=%d", squeeze_h)
  3255. fprintf_param_value(" 2=%d", squeeze_c)
  3256. {
  3257. if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp);
  3258. }
  3259. }
  3260. else if (layer->type == "Threshold")
  3261. {
  3262. ncnn::Threshold* op = (ncnn::Threshold*)layer;
  3263. ncnn::Threshold* op_default = (ncnn::Threshold*)layer_default;
  3264. fprintf_param_value(" 0=%e", threshold)
  3265. }
  3266. else if (layer->type == "UnaryOp")
  3267. {
  3268. ncnn::UnaryOp* op = (ncnn::UnaryOp*)layer;
  3269. ncnn::UnaryOp* op_default = (ncnn::UnaryOp*)layer_default;
  3270. fprintf_param_value(" 0=%d", op_type)
  3271. }
  3272. else if (layer->type == "YoloDetectionOutput")
  3273. {
  3274. ncnn::YoloDetectionOutput* op = (ncnn::YoloDetectionOutput*)layer;
  3275. ncnn::YoloDetectionOutput* op_default = (ncnn::YoloDetectionOutput*)layer_default;
  3276. fprintf_param_value(" 0=%d", num_class)
  3277. fprintf_param_value(" 1=%d", num_box)
  3278. fprintf_param_value(" 2=%e", confidence_threshold)
  3279. fprintf_param_value(" 3=%e", nms_threshold)
  3280. {
  3281. if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp);
  3282. }
  3283. }
  3284. else if (layer->type == "Yolov3DetectionOutput")
  3285. {
  3286. ncnn::Yolov3DetectionOutput* op = (ncnn::Yolov3DetectionOutput*)layer;
  3287. ncnn::Yolov3DetectionOutput* op_default = (ncnn::Yolov3DetectionOutput*)layer_default;
  3288. fprintf_param_value(" 0=%d", num_class)
  3289. fprintf_param_value(" 1=%d", num_box)
  3290. fprintf_param_value(" 2=%e", confidence_threshold)
  3291. fprintf_param_value(" 3=%e", nms_threshold)
  3292. {
  3293. if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp);
  3294. }
  3295. {
  3296. if (!op->mask.empty()) fprintf_param_int_array(5, op->mask, pp);
  3297. }
  3298. {
  3299. if (!op->anchors_scale.empty()) fprintf_param_float_array(6, op->anchors_scale, pp);
  3300. }
  3301. }
  3302. #undef fprintf_param_value
  3303. fprintf(pp, "\n");
  3304. delete layer_default;
  3305. }
  3306. fclose(pp);
  3307. fclose(bp);
  3308. if (mac)
  3309. {
  3310. fprintf(stderr, "mac = %d = %.2f M\n", mac, mac / 1000000.f);
  3311. }
  3312. return 0;
  3313. }
  3314. int main(int argc, char** argv)
  3315. {
  3316. if (argc < 6)
  3317. {
  3318. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag] [cutstart] [cutend]\n", argv[0]);
  3319. return -1;
  3320. }
  3321. const char* inparam = argv[1];
  3322. const char* inbin = argv[2];
  3323. const char* outparam = argv[3];
  3324. const char* outbin = argv[4];
  3325. int flag = atoi(argv[5]);
  3326. const char* cutstartname = nullptr;
  3327. const char* cutendname = nullptr;
  3328. if (argc > 6)
  3329. {
  3330. cutstartname = argv[6];
  3331. }
  3332. if (argc > 7)
  3333. {
  3334. cutendname = argv[7];
  3335. }
  3336. NetOptimize optimizer;
  3337. if (flag == 65536 || flag == 1)
  3338. {
  3339. optimizer.storage_type = 1;
  3340. }
  3341. else
  3342. {
  3343. optimizer.storage_type = 0;
  3344. }
  3345. optimizer.load_param(inparam);
  3346. if (strcmp(inbin, "null") == 0)
  3347. {
  3348. DataReaderFromEmpty dr;
  3349. optimizer.load_model(dr);
  3350. }
  3351. else
  3352. optimizer.load_model(inbin);
  3353. if (optimizer.set_cutparam(cutstartname, cutendname) < 0)
  3354. {
  3355. return -1;
  3356. }
  3357. optimizer.fuse_batchnorm_scale();
  3358. optimizer.fuse_convolution_batchnorm();
  3359. optimizer.fuse_convolution_mul();
  3360. optimizer.fuse_convolution_add();
  3361. optimizer.fuse_convolutiondepthwise_batchnorm();
  3362. optimizer.fuse_convolutiondepthwise_mul();
  3363. optimizer.fuse_convolutiondepthwise_add();
  3364. optimizer.fuse_deconvolution_batchnorm();
  3365. optimizer.fuse_deconvolution_mul();
  3366. optimizer.fuse_deconvolution_add();
  3367. optimizer.fuse_deconvolutiondepthwise_batchnorm();
  3368. optimizer.fuse_innerproduct_batchnorm();
  3369. optimizer.fuse_innerproduct_add();
  3370. optimizer.fuse_innerproduct_dropout();
  3371. optimizer.replace_reduction_with_global_pooling();
  3372. optimizer.replace_prelu_with_leaky_relu();
  3373. optimizer.fuse_convolution_activation();
  3374. optimizer.fuse_convolutiondepthwise_activation();
  3375. optimizer.fuse_deconvolution_activation();
  3376. optimizer.fuse_deconvolutiondepthwise_activation();
  3377. optimizer.fuse_innerproduct_activation();
  3378. optimizer.fuse_memorydata_binaryop();
  3379. optimizer.fuse_binaryop_eltwise();
  3380. optimizer.eliminate_dropout();
  3381. optimizer.eliminate_pooling1x1();
  3382. optimizer.eliminate_noop();
  3383. optimizer.eliminate_flatten_after_global_pooling();
  3384. optimizer.eliminate_reshape_after_global_pooling();
  3385. optimizer.eliminate_reshape_before_binaryop();
  3386. optimizer.replace_convolution_with_innerproduct_after_global_pooling();
  3387. optimizer.replace_convolution_with_innerproduct_after_innerproduct();
  3388. optimizer.eliminate_flatten_after_innerproduct();
  3389. optimizer.eliminate_orphaned_memorydata();
  3390. optimizer.shape_inference();
  3391. optimizer.estimate_memory_footprint();
  3392. optimizer.save(outparam, outbin);
  3393. return 0;
  3394. }