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