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