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 97 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
7 years ago
7 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
6 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952
  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 "net.h"
  23. #include "layer.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/hardsigmoid.h"
  43. #include "layer/hardswish.h"
  44. #include "layer/innerproduct.h"
  45. #include "layer/input.h"
  46. #include "layer/instancenorm.h"
  47. #include "layer/interp.h"
  48. #include "layer/log.h"
  49. #include "layer/lrn.h"
  50. #include "layer/lstm.h"
  51. #include "layer/memorydata.h"
  52. #include "layer/mvn.h"
  53. #include "layer/normalize.h"
  54. #include "layer/padding.h"
  55. #include "layer/permute.h"
  56. #include "layer/pixelshuffle.h"
  57. #include "layer/pooling.h"
  58. #include "layer/power.h"
  59. #include "layer/prelu.h"
  60. #include "layer/priorbox.h"
  61. #include "layer/proposal.h"
  62. #include "layer/psroipooling.h"
  63. #include "layer/quantize.h"
  64. #include "layer/reduction.h"
  65. #include "layer/relu.h"
  66. #include "layer/reorg.h"
  67. #include "layer/requantize.h"
  68. #include "layer/reshape.h"
  69. #include "layer/roialign.h"
  70. #include "layer/roipooling.h"
  71. #include "layer/scale.h"
  72. #include "layer/slice.h"
  73. #include "layer/shufflechannel.h"
  74. #include "layer/softmax.h"
  75. #include "layer/squeeze.h"
  76. #include "layer/threshold.h"
  77. #include "layer/unaryop.h"
  78. #include "layer/yolodetectionoutput.h"
  79. #include "layer/yolov3detectionoutput.h"
  80. #if defined(__aarch64__) && defined(LINUX)
  81. #include <locale>
  82. #include <chrono>
  83. #include <random>
  84. #include <limits>
  85. #include <cassert>
  86. #define TEXT_GREEN "\033[32m"
  87. #define TEXT_YELLOW "\033[33m"
  88. #define TEXT_RED "\033[31m"
  89. #define CLR "\033[0m"
  90. #endif // defined(__aarch64__) && defined(LINUX)
  91. class DataReaderFromEmpty : public ncnn::DataReader
  92. {
  93. public:
  94. virtual int scan(const char* format, void* p) const { return 0; }
  95. virtual size_t read(void* /*buf*/, size_t size) const { return size; }
  96. };
  97. class NetOptimize : public ncnn::Net
  98. {
  99. public:
  100. // 0=fp32 1=fp16
  101. int storage_type;
  102. public:
  103. int fuse_batchnorm_scale();
  104. int fuse_convolution_batchnorm();
  105. int fuse_convolutiondepthwise_batchnorm();
  106. int fuse_deconvolution_batchnorm();
  107. int fuse_deconvolutiondepthwise_batchnorm();
  108. int fuse_innerproduct_batchnorm();
  109. int fuse_innerproduct_dropout();
  110. int fuse_convolution_activation();
  111. int fuse_convolutiondepthwise_activation();
  112. int fuse_deconvolution_activation();
  113. int fuse_deconvolutiondepthwise_activation();
  114. int fuse_innerproduct_activation();
  115. int fuse_memorydata_binaryop();
  116. int fuse_binaryop_eltwise();
  117. int eliminate_dropout();
  118. int eliminate_pooling1x1();
  119. int eliminate_noop();
  120. int eliminate_orphaned_memorydata();
  121. int eliminate_flatten_after_global_pooling();
  122. int eliminate_reshape_after_global_pooling();
  123. int eliminate_flatten_after_innerproduct();
  124. int eliminate_reshape_before_binaryop();
  125. int replace_convolution_with_innerproduct_after_global_pooling();
  126. int replace_convolution_with_innerproduct_after_innerproduct();
  127. int shape_inference();
  128. public:
  129. int fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp);
  130. int fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp);
  131. int fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp);
  132. int fwrite_weight_data(const ncnn::Mat& data, FILE* bp);
  133. int save(const char* parampath, const char* binpath);
  134. #if defined(__aarch64__) && defined(LINUX)
  135. void gauss_random(ncnn::Mat &m);
  136. void find_fastest_fp32_conv(const char* name, int w, int h, int c);
  137. int support_fp32_conv_type(const ncnn::Convolution* op, const ncnn::Mat& mat, const int type);
  138. #endif
  139. };
  140. #if defined(__aarch64__) && defined(LINUX)
  141. void NetOptimize::gauss_random(ncnn::Mat &m)
  142. {
  143. std::random_device rd;
  144. std::mt19937 gen(rd());
  145. std::normal_distribution<float> d(1.0f, 1.0f);
  146. int size = m.total();
  147. for (int i = 0; i < size; ++i)
  148. {
  149. m[i] = d(gen);
  150. }
  151. }
  152. void NetOptimize::find_fastest_fp32_conv(const char* dataname, int w, int h, int c)
  153. {
  154. ncnn::PoolAllocator allocator;
  155. allocator.clear();
  156. ncnn::Option opt;
  157. // embeded system generally use single thread
  158. opt.num_threads = 1;
  159. const size_t layer_count = layers.size();
  160. ncnn::Extractor ex = create_extractor();
  161. ncnn::Mat input(w, h, c);
  162. if (ex.input(dataname, input) < 0)
  163. {
  164. fprintf(stderr, "set input failed, check dataname.\n");
  165. return;
  166. }
  167. const char* IMPL_NAME[6] = {"baseline", "winograd", "pointwise", "im2col", "direct", "conv3x3s2"};
  168. for (int i = 0; i < layer_count; ++i)
  169. {
  170. ncnn::Layer* layer = layers[i];
  171. if (layer->type == "Convolution")
  172. {
  173. ncnn::Convolution* op = (ncnn::Convolution*)layer;
  174. ncnn::Mat bottom_blob;
  175. ncnn::Mat top_blob;
  176. ex.extract(layer->bottoms[0], bottom_blob);
  177. ex.extract(layer->tops[0], top_blob);
  178. if (bottom_blob.empty() || top_blob.empty())
  179. {
  180. continue;
  181. }
  182. ncnn::Mat weight_blob(op->kernel_w, op->kernel_h, bottom_blob.c * top_blob.c);
  183. fprintf(stdout, TEXT_GREEN "Input [w h nc]: %d %d %d\n" CLR, bottom_blob.w, bottom_blob.h, bottom_blob.c);
  184. fprintf(stdout, TEXT_GREEN "Kernel [w h nc]: %d %d %d\n" CLR, op->kernel_w, op->kernel_h, bottom_blob.c * top_blob.c);
  185. fprintf(stdout, TEXT_GREEN "Output [w h nc]: %d %d %d\n" CLR, top_blob.w, top_blob.h, top_blob.c);
  186. // randomize input and kernel
  187. gauss_random(bottom_blob);
  188. // try every implementation
  189. double min_cost = std::numeric_limits<double>::max();
  190. int best_type = 0;
  191. // how much conv implementation type ncnn has ?
  192. for (int type = 1; type <= 5; ++type)
  193. {
  194. int support = support_fp32_conv_type(op, bottom_blob, type);
  195. if (support < 1)
  196. {
  197. // implementation type mismatch convolution configuration, skip
  198. continue;
  199. }
  200. op->impl_type = type;
  201. auto start = std::chrono::high_resolution_clock::now();
  202. const int NREPEATS = 20;
  203. op->create_pipeline(opt);
  204. for (int repeat = 0; repeat < NREPEATS; ++repeat)
  205. {
  206. op->forward(top_blob, bottom_blob, opt);
  207. }
  208. op->destroy_pipeline(opt);
  209. auto stop = std::chrono::high_resolution_clock::now();
  210. double cur_cost = std::chrono::duration<double, std::micro>(stop-start).count() / NREPEATS;
  211. fprintf(stdout, TEXT_GREEN "%s cost %0.3lfms \n" CLR, IMPL_NAME[type], cur_cost/1000);
  212. if (cur_cost < min_cost)
  213. {
  214. min_cost = cur_cost;
  215. best_type = type;
  216. }
  217. }
  218. op->impl_type = best_type;
  219. fprintf(stdout, TEXT_YELLOW "%d: %s use %s \n\n" CLR, i, layer->name.c_str(), IMPL_NAME[op->impl_type]);
  220. }
  221. }
  222. }
  223. int NetOptimize::support_fp32_conv_type(const ncnn::Convolution* op, const ncnn::Mat& bottom, const int type)
  224. {
  225. // not baseline, then k_h == k_w and s_h == s_w
  226. // no dilation conv shall be allowed
  227. if (op->kernel_w != op->kernel_h ||
  228. op->stride_w != op->stride_h ||
  229. op->dilation_w != op->dilation_h ||
  230. op->dilation_h != 1)
  231. {
  232. return -1;
  233. }
  234. // (kernel, stride) in {(1, 1), (1, 2), (2, 1), (3, 1), (3, 2), (4, 4), (5, 1), (5, 2), (7, 1), (7, 2)}
  235. const int support_table[7][4] =
  236. {
  237. {1, 1, 0, 0},
  238. {1, 0, 0, 0},
  239. {1, 1, 0, 0},
  240. {0, 0, 0, 1},
  241. {1, 1, 0, 0},
  242. {0, 0, 0, 0},
  243. {1, 1, 0, 0}
  244. };
  245. // kernel_size x stride
  246. const int kernel = op->kernel_h,
  247. stride = op->stride_h;
  248. // if match prequisation
  249. switch(type)
  250. {
  251. case 1:
  252. // winograd
  253. if (kernel != 3 || stride != 1){
  254. return -1;
  255. }
  256. break;
  257. case 2:
  258. // pointwise
  259. // input_h == 1, input_w == 1, dilation == 1, stride == 1
  260. if (bottom.h != 1 || bottom.w != 1 || stride != 1)
  261. {
  262. return -1;
  263. }
  264. break;
  265. case 3:
  266. // im2col
  267. break;
  268. case 4:
  269. // direct conv
  270. if (support_table[kernel-1][stride-1] == 0)
  271. {
  272. return -1;
  273. }
  274. break;
  275. case 5:
  276. // conv3x3s2
  277. // kernel == 3 and stride == 2
  278. if (kernel != 3 || stride != 2)
  279. {
  280. return -1;
  281. }
  282. break;
  283. default:
  284. fprintf(stderr, TEXT_RED "unrecognize convolution impl type: %d" CLR, type);
  285. break;
  286. }
  287. return 1;
  288. }
  289. #endif // defined(__aarch64__) && defined(LINUX)
  290. int NetOptimize::fuse_batchnorm_scale()
  291. {
  292. const size_t layer_count = layers.size();
  293. for (int i=0; i<layer_count; i++)
  294. {
  295. if (layers[i]->type != "BatchNorm")
  296. continue;
  297. // BatchNorm - Scale
  298. int top_blob_index = layers[i]->tops[0];
  299. int j = i + 1;
  300. for (; j<layer_count; j++)
  301. {
  302. if (layers[j]->type != "Scale")
  303. continue;
  304. if (layers[j]->bottoms.size() != 1)
  305. continue;
  306. if (layers[j]->bottoms[0] == top_blob_index)
  307. break;
  308. }
  309. if (j == layer_count)
  310. continue;
  311. // fuse BatchNorm - Scale to BatchNorm
  312. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[i];
  313. ncnn::Scale* scale = (ncnn::Scale*)layers[j];
  314. fprintf(stderr, "fuse_batchnorm_scale %s %s\n", batchnorm->name.c_str(), scale->name.c_str());
  315. {
  316. // v = ((v - mean) / sqrt(var + eps) * slope + bias) * s + b
  317. // = (v - mean) / sqrt(var + eps) * (slope * s) + (bias * s + b)
  318. int channels = batchnorm->channels;
  319. float* slope = batchnorm->slope_data;
  320. float* bias = batchnorm->bias_data;
  321. for (int q=0; q<channels; q++)
  322. {
  323. slope[q] = slope[q] * scale->scale_data[q];
  324. if (scale->bias_term)
  325. bias[q] = bias[q] * scale->scale_data[q] + scale->bias_data[q];
  326. else
  327. bias[q] = bias[q] * scale->scale_data[q];
  328. }
  329. }
  330. int top_blob_index_final = scale->tops[0];
  331. batchnorm->tops[0] = top_blob_index_final;
  332. blobs[top_blob_index_final].producer = i;
  333. scale->type = "ncnnfused";
  334. }
  335. return 0;
  336. }
  337. int NetOptimize::fuse_convolution_batchnorm()
  338. {
  339. const size_t layer_count = layers.size();
  340. for (int i=0; i<layer_count; i++)
  341. {
  342. if (layers[i]->type != "Convolution")
  343. continue;
  344. // Convolution - BatchNorm
  345. int top_blob_index = layers[i]->tops[0];
  346. int j = i + 1;
  347. for (; j<layer_count; j++)
  348. {
  349. if (layers[j]->type != "BatchNorm")
  350. continue;
  351. if (layers[j]->bottoms.size() != 1)
  352. continue;
  353. if (layers[j]->bottoms[0] == top_blob_index)
  354. break;
  355. }
  356. if (j == layer_count)
  357. continue;
  358. // fuse Convolution - BatchNorm to Convolution
  359. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  360. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  361. fprintf(stderr, "fuse_convolution_batchnorm %s %s\n", convolution->name.c_str(), batchnorm->name.c_str());
  362. {
  363. int channels = batchnorm->channels;
  364. float eps = batchnorm->eps;
  365. // a = bias - slope * mean / sqrt(var + eps)
  366. // b = slope / sqrt(var + eps)
  367. // value = value * b + a
  368. std::vector<float> a(channels);
  369. std::vector<float> b(channels);
  370. for (int i=0; i<channels; i++)
  371. {
  372. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  373. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  374. b[i] = batchnorm->slope_data[i] / sqrt_var;
  375. }
  376. if (convolution->bias_term == 0)
  377. {
  378. // init bias as zero
  379. convolution->bias_term = 1;
  380. convolution->bias_data = ncnn::Mat(channels);
  381. convolution->bias_data.fill(0.f);
  382. }
  383. const int weight_per_outch = convolution->weight_data_size / channels;
  384. float* weight = convolution->weight_data;
  385. float* bias = convolution->bias_data;
  386. for (int i=0; i<channels; i++)
  387. {
  388. float* conv_weight_outch = weight + weight_per_outch * i;
  389. for (int j=0; j<weight_per_outch; j++)
  390. {
  391. conv_weight_outch[j] *= b[i];
  392. }
  393. bias[i] = bias[i] * b[i] + a[i];
  394. }
  395. }
  396. int top_blob_index_final = batchnorm->tops[0];
  397. convolution->tops[0] = top_blob_index_final;
  398. blobs[top_blob_index_final].producer = i;
  399. batchnorm->type = "ncnnfused";
  400. }
  401. return 0;
  402. }
  403. int NetOptimize::fuse_convolutiondepthwise_batchnorm()
  404. {
  405. const size_t layer_count = layers.size();
  406. for (int i=0; i<layer_count; i++)
  407. {
  408. if (layers[i]->type != "ConvolutionDepthWise")
  409. continue;
  410. // ConvolutionDepthWise - BatchNorm
  411. int top_blob_index = layers[i]->tops[0];
  412. int j = i + 1;
  413. for (; j<layer_count; j++)
  414. {
  415. if (layers[j]->type != "BatchNorm")
  416. continue;
  417. if (layers[j]->bottoms.size() != 1)
  418. continue;
  419. if (layers[j]->bottoms[0] == top_blob_index)
  420. break;
  421. }
  422. if (j == layer_count)
  423. continue;
  424. // fuse ConvolutionDepthWise - BatchNorm to ConvolutionDepthWise
  425. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  426. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  427. fprintf(stderr, "fuse_convolutiondepthwise_batchnorm %s %s\n", convolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  428. {
  429. int channels = batchnorm->channels;
  430. float eps = batchnorm->eps;
  431. // a = bias - slope * mean / sqrt(var + eps)
  432. // b = slope / sqrt(var + eps)
  433. // value = value * b + a
  434. std::vector<float> a(channels);
  435. std::vector<float> b(channels);
  436. for (int i=0; i<channels; i++)
  437. {
  438. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  439. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  440. b[i] = batchnorm->slope_data[i] / sqrt_var;
  441. }
  442. if (convolutiondepthwise->bias_term == 0)
  443. {
  444. // init bias as zero
  445. convolutiondepthwise->bias_term = 1;
  446. convolutiondepthwise->bias_data = ncnn::Mat(channels);
  447. convolutiondepthwise->bias_data.fill(0.f);
  448. }
  449. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  450. float* weight = convolutiondepthwise->weight_data;
  451. float* bias = convolutiondepthwise->bias_data;
  452. for (int i=0; i<channels; i++)
  453. {
  454. float* conv_weight_outch = weight + weight_per_outch * i;
  455. for (int j=0; j<weight_per_outch; j++)
  456. {
  457. conv_weight_outch[j] *= b[i];
  458. }
  459. bias[i] = bias[i] * b[i] + a[i];
  460. }
  461. }
  462. int top_blob_index_final = batchnorm->tops[0];
  463. convolutiondepthwise->tops[0] = top_blob_index_final;
  464. blobs[top_blob_index_final].producer = i;
  465. batchnorm->type = "ncnnfused";
  466. }
  467. return 0;
  468. }
  469. int NetOptimize::fuse_deconvolution_batchnorm()
  470. {
  471. const size_t layer_count = layers.size();
  472. for (int i=0; i<layer_count; i++)
  473. {
  474. if (layers[i]->type != "Deconvolution")
  475. continue;
  476. // Deconvolution - BatchNorm
  477. int top_blob_index = layers[i]->tops[0];
  478. int j = i + 1;
  479. for (; j<layer_count; j++)
  480. {
  481. if (layers[j]->type != "BatchNorm")
  482. continue;
  483. if (layers[j]->bottoms.size() != 1)
  484. continue;
  485. if (layers[j]->bottoms[0] == top_blob_index)
  486. break;
  487. }
  488. if (j == layer_count)
  489. continue;
  490. // fuse Deconvolution - BatchNorm to Deconvolution
  491. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  492. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  493. fprintf(stderr, "fuse_deconvolution_batchnorm %s %s\n", deconvolution->name.c_str(), batchnorm->name.c_str());
  494. {
  495. int channels = batchnorm->channels;
  496. float eps = batchnorm->eps;
  497. // a = bias - slope * mean / sqrt(var + eps)
  498. // b = slope / sqrt(var + eps)
  499. // value = value * b + a
  500. std::vector<float> a(channels);
  501. std::vector<float> b(channels);
  502. for (int i=0; i<channels; i++)
  503. {
  504. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  505. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  506. b[i] = batchnorm->slope_data[i] / sqrt_var;
  507. }
  508. if (deconvolution->bias_term == 0)
  509. {
  510. // init bias as zero
  511. deconvolution->bias_term = 1;
  512. deconvolution->bias_data = ncnn::Mat(channels);
  513. deconvolution->bias_data.fill(0.f);
  514. }
  515. const int weight_per_outch = deconvolution->weight_data_size / channels;
  516. float* weight = deconvolution->weight_data;
  517. float* bias = deconvolution->bias_data;
  518. for (int i=0; i<channels; i++)
  519. {
  520. float* conv_weight_outch = weight + weight_per_outch * i;
  521. for (int j=0; j<weight_per_outch; j++)
  522. {
  523. conv_weight_outch[j] *= b[i];
  524. }
  525. bias[i] = bias[i] * b[i] + a[i];
  526. }
  527. }
  528. int top_blob_index_final = batchnorm->tops[0];
  529. deconvolution->tops[0] = top_blob_index_final;
  530. blobs[top_blob_index_final].producer = i;
  531. batchnorm->type = "ncnnfused";
  532. }
  533. return 0;
  534. }
  535. int NetOptimize::fuse_deconvolutiondepthwise_batchnorm()
  536. {
  537. const size_t layer_count = layers.size();
  538. for (int i=0; i<layer_count; i++)
  539. {
  540. if (layers[i]->type != "DeconvolutionDepthWise")
  541. continue;
  542. // DeconvolutionDepthWise - BatchNorm
  543. int top_blob_index = layers[i]->tops[0];
  544. int j = i + 1;
  545. for (; j<layer_count; j++)
  546. {
  547. if (layers[j]->type != "BatchNorm")
  548. continue;
  549. if (layers[j]->bottoms.size() != 1)
  550. continue;
  551. if (layers[j]->bottoms[0] == top_blob_index)
  552. break;
  553. }
  554. if (j == layer_count)
  555. continue;
  556. // fuse DeconvolutionDepthWise - BatchNorm to DeconvolutionDepthWise
  557. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  558. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  559. fprintf(stderr, "fuse_deconvolutiondepthwise_batchnorm %s %s\n", deconvolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  560. {
  561. int channels = batchnorm->channels;
  562. float eps = batchnorm->eps;
  563. // a = bias - slope * mean / sqrt(var + eps)
  564. // b = slope / sqrt(var + eps)
  565. // value = value * b + a
  566. std::vector<float> a(channels);
  567. std::vector<float> b(channels);
  568. for (int i=0; i<channels; i++)
  569. {
  570. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  571. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  572. b[i] = batchnorm->slope_data[i] / sqrt_var;
  573. }
  574. if (deconvolutiondepthwise->bias_term == 0)
  575. {
  576. // init bias as zero
  577. deconvolutiondepthwise->bias_term = 1;
  578. deconvolutiondepthwise->bias_data = ncnn::Mat(channels);
  579. deconvolutiondepthwise->bias_data.fill(0.f);
  580. }
  581. const int weight_per_outch = deconvolutiondepthwise->weight_data_size / channels;
  582. float* weight = deconvolutiondepthwise->weight_data;
  583. float* bias = deconvolutiondepthwise->bias_data;
  584. for (int i=0; i<channels; i++)
  585. {
  586. float* conv_weight_outch = weight + weight_per_outch * i;
  587. for (int j=0; j<weight_per_outch; j++)
  588. {
  589. conv_weight_outch[j] *= b[i];
  590. }
  591. bias[i] = bias[i] * b[i] + a[i];
  592. }
  593. }
  594. int top_blob_index_final = batchnorm->tops[0];
  595. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  596. blobs[top_blob_index_final].producer = i;
  597. batchnorm->type = "ncnnfused";
  598. }
  599. return 0;
  600. }
  601. int NetOptimize::fuse_innerproduct_batchnorm()
  602. {
  603. const size_t layer_count = layers.size();
  604. for (int i=0; i<layer_count; i++)
  605. {
  606. if (layers[i]->type != "InnerProduct")
  607. continue;
  608. // InnerProduct - BatchNorm
  609. int top_blob_index = layers[i]->tops[0];
  610. int j = i + 1;
  611. for (; j<layer_count; j++)
  612. {
  613. if (layers[j]->type != "BatchNorm")
  614. continue;
  615. if (layers[j]->bottoms.size() != 1)
  616. continue;
  617. if (layers[j]->bottoms[0] == top_blob_index)
  618. break;
  619. }
  620. if (j == layer_count)
  621. continue;
  622. // fuse InnerProduct - BatchNorm to InnerProduct
  623. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  624. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  625. fprintf(stderr, "fuse_innerproduct_batchnorm %s %s\n", innerproduct->name.c_str(), batchnorm->name.c_str());
  626. {
  627. int channels = batchnorm->channels;
  628. float eps = batchnorm->eps;
  629. // a = bias - slope * mean / sqrt(var + eps)
  630. // b = slope / sqrt(var + eps)
  631. // value = value * b + a
  632. std::vector<float> a(channels);
  633. std::vector<float> b(channels);
  634. for (int i=0; i<channels; i++)
  635. {
  636. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  637. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  638. b[i] = batchnorm->slope_data[i] / sqrt_var;
  639. }
  640. if (innerproduct->bias_term == 0)
  641. {
  642. // init bias as zero
  643. innerproduct->bias_term = 1;
  644. innerproduct->bias_data = ncnn::Mat(channels);
  645. innerproduct->bias_data.fill(0.f);
  646. }
  647. const int weight_per_outch = innerproduct->weight_data_size / channels;
  648. float* weight = innerproduct->weight_data;
  649. float* bias = innerproduct->bias_data;
  650. for (int i=0; i<channels; i++)
  651. {
  652. float* conv_weight_outch = weight + weight_per_outch * i;
  653. for (int j=0; j<weight_per_outch; j++)
  654. {
  655. conv_weight_outch[j] *= b[i];
  656. }
  657. bias[i] = bias[i] * b[i] + a[i];
  658. }
  659. }
  660. int top_blob_index_final = batchnorm->tops[0];
  661. innerproduct->tops[0] = top_blob_index_final;
  662. blobs[top_blob_index_final].producer = i;
  663. batchnorm->type = "ncnnfused";
  664. }
  665. return 0;
  666. }
  667. int NetOptimize::fuse_innerproduct_dropout()
  668. {
  669. const size_t layer_count = layers.size();
  670. for (int i=0; i<layer_count; i++)
  671. {
  672. if (layers[i]->type != "InnerProduct")
  673. continue;
  674. // InnerProduct - Dropout
  675. int top_blob_index = layers[i]->tops[0];
  676. int j = i + 1;
  677. for (; j<layer_count; j++)
  678. {
  679. if (layers[j]->type != "Dropout")
  680. continue;
  681. if (layers[j]->bottoms.size() != 1)
  682. continue;
  683. if (layers[j]->bottoms[0] == top_blob_index)
  684. break;
  685. }
  686. if (j == layer_count)
  687. continue;
  688. // fuse InnerProduct - Dropout to InnerProduct
  689. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  690. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[j];
  691. fprintf(stderr, "fuse_innerproduct_dropout %s %s\n", innerproduct->name.c_str(), dropout->name.c_str());
  692. float scale = dropout->scale;
  693. if (scale != 1.f)
  694. {
  695. const int num_output = innerproduct->num_output;
  696. const int weight_per_outch = innerproduct->weight_data_size / num_output;
  697. float* weight = innerproduct->weight_data;
  698. for (int i=0; i<num_output; i++)
  699. {
  700. float* conv_weight_outch = weight + weight_per_outch * i;
  701. for (int j=0; j<weight_per_outch; j++)
  702. {
  703. conv_weight_outch[j] *= scale;
  704. }
  705. }
  706. if (innerproduct->bias_term)
  707. {
  708. float* bias = innerproduct->bias_data;
  709. for (int i=0; i<num_output; i++)
  710. {
  711. bias[i] *= scale;
  712. }
  713. }
  714. }
  715. int top_blob_index_final = dropout->tops[0];
  716. innerproduct->tops[0] = top_blob_index_final;
  717. blobs[top_blob_index_final].producer = i;
  718. dropout->type = "ncnnfused";
  719. }
  720. return 0;
  721. }
  722. int NetOptimize::fuse_convolution_activation()
  723. {
  724. const size_t layer_count = layers.size();
  725. for (int i=0; i<layer_count; i++)
  726. {
  727. if (layers[i]->type != "Convolution")
  728. continue;
  729. // Convolution - Activation
  730. int top_blob_index = layers[i]->tops[0];
  731. int j = i + 1;
  732. for (; j<layer_count; j++)
  733. {
  734. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  735. continue;
  736. if (layers[j]->bottoms.size() != 1)
  737. continue;
  738. if (layers[j]->bottoms[0] == top_blob_index)
  739. break;
  740. }
  741. if (j == layer_count)
  742. continue;
  743. // fuse Convolution - Activation to Convolution
  744. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  745. ncnn::Layer* activation = layers[j];
  746. fprintf(stderr, "fuse_convolution_activation %s %s\n", convolution->name.c_str(), activation->name.c_str());
  747. if (activation->type == "ReLU")
  748. {
  749. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  750. if (relu->slope == 0.f)
  751. {
  752. convolution->activation_type = 1;
  753. }
  754. else
  755. {
  756. convolution->activation_type = 2;
  757. convolution->activation_params = ncnn::Mat(1);
  758. convolution->activation_params[0] = relu->slope;
  759. }
  760. }
  761. else if (activation->type == "Clip")
  762. {
  763. ncnn::Clip* clip = (ncnn::Clip*)activation;
  764. convolution->activation_type = 3;
  765. convolution->activation_params = ncnn::Mat(2);
  766. convolution->activation_params[0] = clip->min;
  767. convolution->activation_params[1] = clip->max;
  768. }
  769. else if (activation->type == "Sigmoid")
  770. {
  771. convolution->activation_type = 4;
  772. }
  773. int top_blob_index_final = activation->tops[0];
  774. convolution->tops[0] = top_blob_index_final;
  775. blobs[top_blob_index_final].producer = i;
  776. activation->type = "ncnnfused";
  777. }
  778. return 0;
  779. }
  780. int NetOptimize::fuse_convolutiondepthwise_activation()
  781. {
  782. const size_t layer_count = layers.size();
  783. for (int i=0; i<layer_count; i++)
  784. {
  785. if (layers[i]->type != "ConvolutionDepthWise")
  786. continue;
  787. // ConvolutionDepthWise - Activation
  788. int top_blob_index = layers[i]->tops[0];
  789. int j = i + 1;
  790. for (; j<layer_count; j++)
  791. {
  792. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  793. continue;
  794. if (layers[j]->bottoms.size() != 1)
  795. continue;
  796. if (layers[j]->bottoms[0] == top_blob_index)
  797. break;
  798. }
  799. if (j == layer_count)
  800. continue;
  801. // fuse ConvolutionDepthWise - Activation to ConvolutionDepthWise
  802. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  803. ncnn::Layer* activation = layers[j];
  804. fprintf(stderr, "fuse_convolutiondepthwise_activation %s %s\n", convolutiondepthwise->name.c_str(), activation->name.c_str());
  805. if (activation->type == "ReLU")
  806. {
  807. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  808. if (relu->slope == 0.f)
  809. {
  810. convolutiondepthwise->activation_type = 1;
  811. }
  812. else
  813. {
  814. convolutiondepthwise->activation_type = 2;
  815. convolutiondepthwise->activation_params = ncnn::Mat(1);
  816. convolutiondepthwise->activation_params[0] = relu->slope;
  817. }
  818. }
  819. else if (activation->type == "Clip")
  820. {
  821. ncnn::Clip* clip = (ncnn::Clip*)activation;
  822. convolutiondepthwise->activation_type = 3;
  823. convolutiondepthwise->activation_params = ncnn::Mat(2);
  824. convolutiondepthwise->activation_params[0] = clip->min;
  825. convolutiondepthwise->activation_params[1] = clip->max;
  826. }
  827. else if (activation->type == "Sigmoid")
  828. {
  829. convolutiondepthwise->activation_type = 4;
  830. }
  831. int top_blob_index_final = activation->tops[0];
  832. convolutiondepthwise->tops[0] = top_blob_index_final;
  833. blobs[top_blob_index_final].producer = i;
  834. activation->type = "ncnnfused";
  835. }
  836. return 0;
  837. }
  838. int NetOptimize::fuse_deconvolution_activation()
  839. {
  840. const size_t layer_count = layers.size();
  841. for (int i=0; i<layer_count; i++)
  842. {
  843. if (layers[i]->type != "Deconvolution")
  844. continue;
  845. // Deconvolution - Activation
  846. int top_blob_index = layers[i]->tops[0];
  847. int j = i + 1;
  848. for (; j<layer_count; j++)
  849. {
  850. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  851. continue;
  852. if (layers[j]->bottoms.size() != 1)
  853. continue;
  854. if (layers[j]->bottoms[0] == top_blob_index)
  855. break;
  856. }
  857. if (j == layer_count)
  858. continue;
  859. // fuse Deconvolution - Activation to Deconvolution
  860. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  861. ncnn::Layer* activation = layers[j];
  862. fprintf(stderr, "fuse_deconvolution_activation %s %s\n", deconvolution->name.c_str(), activation->name.c_str());
  863. if (activation->type == "ReLU")
  864. {
  865. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  866. if (relu->slope == 0.f)
  867. {
  868. deconvolution->activation_type = 1;
  869. }
  870. else
  871. {
  872. deconvolution->activation_type = 2;
  873. deconvolution->activation_params = ncnn::Mat(1);
  874. deconvolution->activation_params[0] = relu->slope;
  875. }
  876. }
  877. else if (activation->type == "Clip")
  878. {
  879. ncnn::Clip* clip = (ncnn::Clip*)activation;
  880. deconvolution->activation_type = 3;
  881. deconvolution->activation_params = ncnn::Mat(2);
  882. deconvolution->activation_params[0] = clip->min;
  883. deconvolution->activation_params[1] = clip->max;
  884. }
  885. else if (activation->type == "Sigmoid")
  886. {
  887. deconvolution->activation_type = 4;
  888. }
  889. int top_blob_index_final = activation->tops[0];
  890. deconvolution->tops[0] = top_blob_index_final;
  891. blobs[top_blob_index_final].producer = i;
  892. activation->type = "ncnnfused";
  893. }
  894. return 0;
  895. }
  896. int NetOptimize::fuse_deconvolutiondepthwise_activation()
  897. {
  898. const size_t layer_count = layers.size();
  899. for (int i=0; i<layer_count; i++)
  900. {
  901. if (layers[i]->type != "DeconvolutionDepthWise")
  902. continue;
  903. // DeconvolutionDepthWise - Activation
  904. int top_blob_index = layers[i]->tops[0];
  905. int j = i + 1;
  906. for (; j<layer_count; j++)
  907. {
  908. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  909. continue;
  910. if (layers[j]->bottoms.size() != 1)
  911. continue;
  912. if (layers[j]->bottoms[0] == top_blob_index)
  913. break;
  914. }
  915. if (j == layer_count)
  916. continue;
  917. // fuse DeconvolutionDepthWise - Activation to DeconvolutionDepthWise
  918. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  919. ncnn::Layer* activation = layers[j];
  920. fprintf(stderr, "fuse_deconvolutiondepthwise_activation %s %s\n", deconvolutiondepthwise->name.c_str(), activation->name.c_str());
  921. if (activation->type == "ReLU")
  922. {
  923. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  924. if (relu->slope == 0.f)
  925. {
  926. deconvolutiondepthwise->activation_type = 1;
  927. }
  928. else
  929. {
  930. deconvolutiondepthwise->activation_type = 2;
  931. deconvolutiondepthwise->activation_params = ncnn::Mat(1);
  932. deconvolutiondepthwise->activation_params[0] = relu->slope;
  933. }
  934. }
  935. else if (activation->type == "Clip")
  936. {
  937. ncnn::Clip* clip = (ncnn::Clip*)activation;
  938. deconvolutiondepthwise->activation_type = 3;
  939. deconvolutiondepthwise->activation_params = ncnn::Mat(2);
  940. deconvolutiondepthwise->activation_params[0] = clip->min;
  941. deconvolutiondepthwise->activation_params[1] = clip->max;
  942. }
  943. else if (activation->type == "Sigmoid")
  944. {
  945. deconvolutiondepthwise->activation_type = 4;
  946. }
  947. int top_blob_index_final = activation->tops[0];
  948. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  949. blobs[top_blob_index_final].producer = i;
  950. activation->type = "ncnnfused";
  951. }
  952. return 0;
  953. }
  954. int NetOptimize::fuse_innerproduct_activation()
  955. {
  956. const size_t layer_count = layers.size();
  957. for (int i=0; i<layer_count; i++)
  958. {
  959. if (layers[i]->type != "InnerProduct")
  960. continue;
  961. // InnerProduct - Activation
  962. int top_blob_index = layers[i]->tops[0];
  963. int j = i + 1;
  964. for (; j<layer_count; j++)
  965. {
  966. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  967. continue;
  968. if (layers[j]->bottoms.size() != 1)
  969. continue;
  970. if (layers[j]->bottoms[0] == top_blob_index)
  971. break;
  972. }
  973. if (j == layer_count)
  974. continue;
  975. // fuse InnerProduct - Activation to InnerProduct
  976. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  977. ncnn::Layer* activation = layers[j];
  978. fprintf(stderr, "fuse_innerproduct_activation %s %s\n", innerproduct->name.c_str(), activation->name.c_str());
  979. if (activation->type == "ReLU")
  980. {
  981. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  982. if (relu->slope == 0.f)
  983. {
  984. innerproduct->activation_type = 1;
  985. }
  986. else
  987. {
  988. innerproduct->activation_type = 2;
  989. innerproduct->activation_params = ncnn::Mat(1);
  990. innerproduct->activation_params[0] = relu->slope;
  991. }
  992. }
  993. else if (activation->type == "Clip")
  994. {
  995. ncnn::Clip* clip = (ncnn::Clip*)activation;
  996. innerproduct->activation_type = 3;
  997. innerproduct->activation_params = ncnn::Mat(2);
  998. innerproduct->activation_params[0] = clip->min;
  999. innerproduct->activation_params[1] = clip->max;
  1000. }
  1001. else if (activation->type == "Sigmoid")
  1002. {
  1003. innerproduct->activation_type = 4;
  1004. }
  1005. int top_blob_index_final = activation->tops[0];
  1006. innerproduct->tops[0] = top_blob_index_final;
  1007. blobs[top_blob_index_final].producer = i;
  1008. activation->type = "ncnnfused";
  1009. }
  1010. return 0;
  1011. }
  1012. int NetOptimize::fuse_memorydata_binaryop()
  1013. {
  1014. const size_t layer_count = layers.size();
  1015. for (int i=0; i<layer_count; i++)
  1016. {
  1017. if (layers[i]->type != "MemoryData")
  1018. continue;
  1019. // MemoryData - BinaryOp
  1020. int top_blob_index = layers[i]->tops[0];
  1021. int j = i + 1;
  1022. for (; j<layer_count; j++)
  1023. {
  1024. if (layers[j]->type != "BinaryOp")
  1025. continue;
  1026. if (layers[j]->bottoms.size() != 2)
  1027. continue;
  1028. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1029. break;
  1030. }
  1031. if (j == layer_count)
  1032. continue;
  1033. // fuse MemoryData - BinaryOp to BinaryOp
  1034. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[i];
  1035. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1036. int memorydata_index = 1;
  1037. if (binaryop->bottoms[0] == top_blob_index)
  1038. {
  1039. int op_type = binaryop->op_type;
  1040. if (op_type == ncnn::BinaryOp::Operation_ADD
  1041. || op_type == ncnn::BinaryOp::Operation_MUL
  1042. || op_type == ncnn::BinaryOp::Operation_MAX
  1043. || op_type == ncnn::BinaryOp::Operation_MIN)
  1044. {
  1045. memorydata_index = 0;
  1046. }
  1047. else if (op_type == ncnn::BinaryOp::Operation_SUB)
  1048. {
  1049. binaryop->op_type = ncnn::BinaryOp::Operation_RSUB;
  1050. memorydata_index = 0;
  1051. }
  1052. else if (op_type == ncnn::BinaryOp::Operation_DIV)
  1053. {
  1054. binaryop->op_type = ncnn::BinaryOp::Operation_RDIV;
  1055. memorydata_index = 0;
  1056. }
  1057. else
  1058. {
  1059. // non interchangeable binaryop
  1060. continue;
  1061. }
  1062. }
  1063. if (memorydata->w != 1 || memorydata->h != 0 || memorydata->c != 0)
  1064. {
  1065. // not a scalar
  1066. continue;
  1067. }
  1068. float scalar = memorydata->data[0];
  1069. binaryop->with_scalar = 1;
  1070. binaryop->b = scalar;
  1071. fprintf(stderr, "fuse_memorydata_binaryop %s %s\n", memorydata->name.c_str(), binaryop->name.c_str());
  1072. binaryop->bottoms.erase(binaryop->bottoms.begin() + memorydata_index);
  1073. memorydata->type = "ncnnfused";
  1074. }
  1075. return 0;
  1076. }
  1077. int NetOptimize::fuse_binaryop_eltwise()
  1078. {
  1079. const size_t layer_count = layers.size();
  1080. for (int i=0; i<layer_count; i++)
  1081. {
  1082. if (layers[i]->type != "BinaryOp")
  1083. continue;
  1084. if (layers[i]->bottoms.size() != 2)
  1085. continue;
  1086. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[i];
  1087. if (binaryop->op_type != ncnn::BinaryOp::Operation_ADD)
  1088. continue;
  1089. if (binaryop->with_scalar)
  1090. continue;
  1091. // BinaryOp - BinaryOp - BinaryOp
  1092. int bottom_blob_index_0 = binaryop->bottoms[0];
  1093. int bottom_blob_index_1 = binaryop->bottoms[1];
  1094. int j0 = 0;
  1095. for (; j0<i; j0++)
  1096. {
  1097. if (layers[j0]->type != "BinaryOp")
  1098. continue;
  1099. if (layers[j0]->bottoms.size() != 1)
  1100. continue;
  1101. if (((ncnn::BinaryOp*)layers[j0])->op_type != ncnn::BinaryOp::Operation_MUL)
  1102. continue;
  1103. if (layers[j0]->tops[0] == bottom_blob_index_0)
  1104. break;
  1105. }
  1106. int j1 = 0;
  1107. for (; j1<i; j1++)
  1108. {
  1109. if (layers[j1]->type != "BinaryOp")
  1110. continue;
  1111. if (layers[j1]->bottoms.size() != 1)
  1112. continue;
  1113. if (((ncnn::BinaryOp*)layers[j1])->op_type != ncnn::BinaryOp::Operation_MUL)
  1114. continue;
  1115. if (layers[j1]->tops[0] == bottom_blob_index_1)
  1116. break;
  1117. }
  1118. if (j0 == i && j1 == i)
  1119. continue;
  1120. ncnn::BinaryOp* binaryop0 = (ncnn::BinaryOp*)layers[j0];
  1121. ncnn::BinaryOp* binaryop1 = (ncnn::BinaryOp*)layers[j1];
  1122. fprintf(stderr, "fuse_binaryop_eltwise %s %s %s\n", binaryop0->name.c_str(), binaryop1->name.c_str(), binaryop->name.c_str());
  1123. ncnn::Eltwise* eltwise = (ncnn::Eltwise*)ncnn::create_layer("Eltwise");
  1124. eltwise->type = "Eltwise";
  1125. eltwise->name = binaryop->name;
  1126. eltwise->bottoms = binaryop->bottoms;
  1127. eltwise->tops = binaryop->tops;
  1128. ncnn::ParamDict pd;
  1129. eltwise->load_param(pd);
  1130. eltwise->op_type = ncnn::Eltwise::Operation_SUM;
  1131. eltwise->coeffs = ncnn::Mat(2);
  1132. if (j0 != i && j1 != i)
  1133. {
  1134. // fuse BinaryOp - BinaryOp - BinaryOp to Eltwise
  1135. eltwise->coeffs[0] = binaryop0->b;
  1136. eltwise->coeffs[1] = binaryop1->b;
  1137. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1138. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1139. binaryop0->type = "ncnnfused";
  1140. binaryop1->type = "ncnnfused";
  1141. }
  1142. if (j0 != i && j1 == i)
  1143. {
  1144. // fuse BinaryOp - X - BinaryOp to Eltwise
  1145. eltwise->coeffs[0] = binaryop0->b;
  1146. eltwise->coeffs[1] = 1.f;
  1147. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1148. binaryop0->type = "ncnnfused";
  1149. }
  1150. if (j0 == i && j1 != i)
  1151. {
  1152. // fuse X - BinaryOp - BinaryOp to Eltwise
  1153. eltwise->coeffs[0] = 1.f;
  1154. eltwise->coeffs[1] = binaryop1->b;
  1155. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1156. binaryop1->type = "ncnnfused";
  1157. }
  1158. layers[i] = eltwise;
  1159. delete binaryop;
  1160. }
  1161. return 0;
  1162. }
  1163. int NetOptimize::eliminate_dropout()
  1164. {
  1165. const size_t layer_count = layers.size();
  1166. for (int i=0; i<layer_count; i++)
  1167. {
  1168. if (layers[i]->type != "Dropout")
  1169. continue;
  1170. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[i];
  1171. if (dropout->scale != 1.f)
  1172. continue;
  1173. // Any - Dropout
  1174. int bottom_blob_index = layers[i]->bottoms[0];
  1175. int j = i - 1;
  1176. for (; j>=0; j--)
  1177. {
  1178. if (layers[j]->type == "ncnnfused")
  1179. continue;
  1180. if (layers[j]->tops.size() != 1)
  1181. continue;
  1182. if (layers[j]->tops[0] == bottom_blob_index)
  1183. break;
  1184. }
  1185. if (j == -1)
  1186. continue;
  1187. ncnn::Layer* any = layers[j];
  1188. fprintf(stderr, "eliminate_dropout %s %s\n", any->name.c_str(), dropout->name.c_str());
  1189. int top_blob_index_final = dropout->tops[0];
  1190. any->tops[0] = top_blob_index_final;
  1191. blobs[top_blob_index_final].producer = j;
  1192. dropout->type = "ncnnfused";
  1193. }
  1194. return 0;
  1195. }
  1196. int NetOptimize::eliminate_pooling1x1()
  1197. {
  1198. const size_t layer_count = layers.size();
  1199. for (int i=0; i<layer_count; i++)
  1200. {
  1201. if (layers[i]->type != "Pooling")
  1202. continue;
  1203. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1204. if (pooling->pad_left != 0 || pooling->pad_right != 0 || pooling->pad_top != 0 || pooling->pad_bottom != 0)
  1205. continue;
  1206. if (pooling->kernel_w != 1 || pooling->kernel_h != 1 || pooling->stride_w != 1 || pooling->stride_h != 1)
  1207. continue;
  1208. if (pooling->global_pooling != 0)
  1209. continue;
  1210. // Any - Pooling
  1211. int bottom_blob_index = layers[i]->bottoms[0];
  1212. int top_i = -1;
  1213. int j = i - 1;
  1214. for (; j>=0; j--)
  1215. {
  1216. if (layers[j]->type == "ncnnfused")
  1217. continue;
  1218. for (int k=0; k<layers[j]->tops.size(); k++)
  1219. {
  1220. if (layers[j]->tops[k] == bottom_blob_index)
  1221. {
  1222. top_i = k;
  1223. break;
  1224. }
  1225. }
  1226. if (top_i != -1)
  1227. break;
  1228. }
  1229. if (j == -1)
  1230. continue;
  1231. ncnn::Layer* any = layers[j];
  1232. fprintf(stderr, "eliminate_pooling1x1 %s %s\n", any->name.c_str(), pooling->name.c_str());
  1233. int top_blob_index_final = pooling->tops[0];
  1234. any->tops[top_i] = top_blob_index_final;
  1235. blobs[top_blob_index_final].producer = j;
  1236. pooling->type = "ncnnfused";
  1237. }
  1238. return 0;
  1239. }
  1240. int NetOptimize::eliminate_noop()
  1241. {
  1242. const size_t layer_count = layers.size();
  1243. for (int i=0; i<layer_count; i++)
  1244. {
  1245. if (layers[i]->type != "Noop")
  1246. continue;
  1247. ncnn::Layer* noop = layers[i];
  1248. if (noop->bottoms.empty())
  1249. {
  1250. // Noop
  1251. fprintf(stderr, "eliminate_noop %s\n", noop->name.c_str());
  1252. size_t top_blob_count = noop->tops.size();
  1253. for (int k=0; k<top_blob_count; k++)
  1254. {
  1255. int top_blob_index_final = noop->tops[k];
  1256. blobs[top_blob_index_final].producer = -1;
  1257. }
  1258. noop->type = "ncnnfused";
  1259. continue;
  1260. }
  1261. // Any - Noop
  1262. int bottom_blob_index = layers[i]->bottoms[0];
  1263. int j = i - 1;
  1264. for (; j>=0; j--)
  1265. {
  1266. if (layers[j]->type == "ncnnfused")
  1267. continue;
  1268. if (layers[j]->tops.size() != 1)
  1269. continue;
  1270. if (layers[j]->tops[0] == bottom_blob_index)
  1271. break;
  1272. }
  1273. if (j == -1)
  1274. continue;
  1275. ncnn::Layer* any = layers[j];
  1276. fprintf(stderr, "eliminate_noop %s %s\n", any->name.c_str(), noop->name.c_str());
  1277. size_t top_blob_count = std::min(noop->tops.size(), any->tops.size());
  1278. for (int k=0; k<top_blob_count; k++)
  1279. {
  1280. int top_blob_index_final = noop->tops[k];
  1281. any->tops[k] = top_blob_index_final;
  1282. blobs[top_blob_index_final].producer = j;
  1283. }
  1284. noop->type = "ncnnfused";
  1285. }
  1286. return 0;
  1287. }
  1288. int NetOptimize::eliminate_orphaned_memorydata()
  1289. {
  1290. const size_t layer_count = layers.size();
  1291. for (int i=0; i<layer_count; i++)
  1292. {
  1293. if (layers[i]->type != "MemoryData")
  1294. continue;
  1295. // MemoryData - X
  1296. int top_blob_index = layers[i]->tops[0];
  1297. int j = i + 1;
  1298. for (; j<layer_count; j++)
  1299. {
  1300. if (layers[j]->type == "ncnnfused")
  1301. continue;
  1302. bool orphaned = true;
  1303. for (int k=0; k<layers[j]->bottoms.size(); k++)
  1304. {
  1305. if (layers[j]->bottoms[k] == top_blob_index)
  1306. {
  1307. orphaned = false;
  1308. break;
  1309. }
  1310. }
  1311. if (!orphaned)
  1312. break;
  1313. }
  1314. if (j < layer_count)
  1315. continue;
  1316. // assert orphaned == true
  1317. fprintf(stderr, "eliminate_orphaned_memorydata %s\n", layers[i]->name.c_str());
  1318. layers[i]->type = "ncnnfused";
  1319. }
  1320. return 0;
  1321. }
  1322. int NetOptimize::eliminate_reshape_after_global_pooling()
  1323. {
  1324. const size_t layer_count = layers.size();
  1325. for (int i=0; i<layer_count; i++)
  1326. {
  1327. if (layers[i]->type != "Pooling")
  1328. continue;
  1329. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1330. if (pooling->global_pooling == 0)
  1331. continue;
  1332. // Pooling - Reshape
  1333. int top_blob_index = layers[i]->tops[0];
  1334. int j = i + 1;
  1335. for (; j<layer_count; j++)
  1336. {
  1337. if (layers[j]->type != "Reshape")
  1338. continue;
  1339. if (layers[j]->bottoms.size() != 1)
  1340. continue;
  1341. if (layers[j]->bottoms[0] == top_blob_index)
  1342. break;
  1343. }
  1344. if (j == layer_count)
  1345. continue;
  1346. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[j];
  1347. if (reshape->h != -233 || reshape->c != -233 || reshape->permute != 0)
  1348. continue;
  1349. fprintf(stderr, "eliminate_reshape_after_global_pooling %s %s\n", pooling->name.c_str(), reshape->name.c_str());
  1350. int top_blob_index_final = reshape->tops[0];
  1351. pooling->tops[0] = top_blob_index_final;
  1352. blobs[top_blob_index_final].producer = i;
  1353. reshape->type = "ncnnfused";
  1354. }
  1355. return 0;
  1356. }
  1357. int NetOptimize::eliminate_flatten_after_global_pooling()
  1358. {
  1359. const size_t layer_count = layers.size();
  1360. for (int i=0; i<layer_count; i++)
  1361. {
  1362. if (layers[i]->type != "Pooling")
  1363. continue;
  1364. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1365. if (pooling->global_pooling == 0)
  1366. continue;
  1367. // Pooling - Flatten
  1368. int top_blob_index = layers[i]->tops[0];
  1369. int j = i + 1;
  1370. for (; j<layer_count; j++)
  1371. {
  1372. if (layers[j]->type != "Flatten")
  1373. continue;
  1374. if (layers[j]->bottoms.size() != 1)
  1375. continue;
  1376. if (layers[j]->bottoms[0] == top_blob_index)
  1377. break;
  1378. }
  1379. if (j == layer_count)
  1380. continue;
  1381. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1382. fprintf(stderr, "eliminate_flatten_after_global_pooling %s %s\n", pooling->name.c_str(), flatten->name.c_str());
  1383. int top_blob_index_final = flatten->tops[0];
  1384. pooling->tops[0] = top_blob_index_final;
  1385. blobs[top_blob_index_final].producer = i;
  1386. flatten->type = "ncnnfused";
  1387. }
  1388. return 0;
  1389. }
  1390. int NetOptimize::eliminate_flatten_after_innerproduct()
  1391. {
  1392. const size_t layer_count = layers.size();
  1393. for (int i=0; i<layer_count; i++)
  1394. {
  1395. if (layers[i]->type != "InnerProduct")
  1396. continue;
  1397. // InnerProduct - Flatten
  1398. int top_blob_index = layers[i]->tops[0];
  1399. int j = i + 1;
  1400. for (; j<layer_count; j++)
  1401. {
  1402. if (layers[j]->type != "Flatten")
  1403. continue;
  1404. if (layers[j]->bottoms.size() != 1)
  1405. continue;
  1406. if (layers[j]->bottoms[0] == top_blob_index)
  1407. break;
  1408. }
  1409. if (j == layer_count)
  1410. continue;
  1411. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1412. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1413. fprintf(stderr, "eliminate_flatten_after_innerproduct %s %s\n", innerproduct->name.c_str(), flatten->name.c_str());
  1414. int top_blob_index_final = flatten->tops[0];
  1415. innerproduct->tops[0] = top_blob_index_final;
  1416. blobs[top_blob_index_final].producer = i;
  1417. flatten->type = "ncnnfused";
  1418. }
  1419. return 0;
  1420. }
  1421. int NetOptimize::eliminate_reshape_before_binaryop()
  1422. {
  1423. const size_t layer_count = layers.size();
  1424. for (int i=0; i<layer_count; i++)
  1425. {
  1426. if (layers[i]->type != "Reshape")
  1427. continue;
  1428. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[i];
  1429. if (reshape->w != 1 || reshape->h != 1 || reshape->permute != 0)
  1430. continue;
  1431. // Reshape - BinaryOp
  1432. int top_blob_index = layers[i]->tops[0];
  1433. int j = i + 1;
  1434. for (; j<layer_count; j++)
  1435. {
  1436. if (layers[j]->type != "BinaryOp")
  1437. continue;
  1438. if (layers[j]->bottoms.size() != 2)
  1439. continue;
  1440. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1441. break;
  1442. }
  1443. if (j == layer_count)
  1444. continue;
  1445. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1446. fprintf(stderr, "eliminate_reshape_before_binaryop %s %s\n", reshape->name.c_str(), binaryop->name.c_str());
  1447. int bottom_blob_index_final = reshape->bottoms[0];
  1448. if (layers[j]->bottoms[0] == top_blob_index)
  1449. binaryop->bottoms[0] = bottom_blob_index_final;
  1450. if (layers[j]->bottoms[1] == top_blob_index)
  1451. binaryop->bottoms[1] = bottom_blob_index_final;
  1452. blobs[bottom_blob_index_final].consumers.erase(std::find(blobs[bottom_blob_index_final].consumers.begin(), blobs[bottom_blob_index_final].consumers.end(), i));
  1453. blobs[bottom_blob_index_final].consumers.push_back(j);
  1454. reshape->type = "ncnnfused";
  1455. }
  1456. return 0;
  1457. }
  1458. int NetOptimize::replace_convolution_with_innerproduct_after_global_pooling()
  1459. {
  1460. const size_t layer_count = layers.size();
  1461. for (int i=0; i<layer_count; i++)
  1462. {
  1463. if (layers[i]->type != "Pooling")
  1464. continue;
  1465. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1466. if (pooling->global_pooling == 0)
  1467. continue;
  1468. // Pooling - Convolution
  1469. int top_blob_index = layers[i]->tops[0];
  1470. int j = i + 1;
  1471. for (; j<layer_count; j++)
  1472. {
  1473. if (layers[j]->type != "Convolution")
  1474. continue;
  1475. if (layers[j]->bottoms.size() != 1)
  1476. continue;
  1477. if (layers[j]->bottoms[0] == top_blob_index)
  1478. break;
  1479. }
  1480. if (j == layer_count)
  1481. continue;
  1482. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  1483. fprintf(stderr, "replace_convolution_with_innerproduct_after_global_pooling %s %s\n", pooling->name.c_str(), convolution->name.c_str());
  1484. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  1485. innerproduct->type = "InnerProduct";
  1486. innerproduct->name = convolution->name;
  1487. innerproduct->bottoms = convolution->bottoms;
  1488. innerproduct->tops = convolution->tops;
  1489. ncnn::ParamDict pd;
  1490. innerproduct->load_param(pd);
  1491. innerproduct->num_output = convolution->num_output;
  1492. innerproduct->bias_term = convolution->bias_term;
  1493. innerproduct->weight_data_size = convolution->weight_data_size;
  1494. innerproduct->int8_scale_term = convolution->int8_scale_term;
  1495. innerproduct->weight_data = convolution->weight_data;
  1496. innerproduct->bias_data = convolution->bias_data;
  1497. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  1498. innerproduct->bottom_blob_int8_scale = convolution->bottom_blob_int8_scale;
  1499. innerproduct->activation_type = convolution->activation_type;
  1500. innerproduct->activation_params = convolution->activation_params;
  1501. layers[j] = innerproduct;
  1502. delete convolution;
  1503. }
  1504. return 0;
  1505. }
  1506. int NetOptimize::replace_convolution_with_innerproduct_after_innerproduct()
  1507. {
  1508. const size_t layer_count = layers.size();
  1509. for (;;)
  1510. {
  1511. bool replaced = false;
  1512. for (int i=0; i<layer_count; i++)
  1513. {
  1514. if (layers[i]->type != "InnerProduct")
  1515. continue;
  1516. // InnerProduct - Convolution
  1517. int top_blob_index = layers[i]->tops[0];
  1518. int j = i + 1;
  1519. for (; j<layer_count; j++)
  1520. {
  1521. if (layers[j]->type != "Convolution")
  1522. continue;
  1523. if (layers[j]->bottoms.size() != 1)
  1524. continue;
  1525. if (layers[j]->bottoms[0] == top_blob_index)
  1526. break;
  1527. }
  1528. if (j == layer_count)
  1529. continue;
  1530. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1531. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  1532. fprintf(stderr, "replace_convolution_with_innerproduct_after_innerproduct %s %s\n", innerproduct->name.c_str(), convolution->name.c_str());
  1533. ncnn::InnerProduct* innerproduct2 = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  1534. innerproduct2->type = "InnerProduct";
  1535. innerproduct2->name = convolution->name;
  1536. innerproduct2->bottoms = convolution->bottoms;
  1537. innerproduct2->tops = convolution->tops;
  1538. ncnn::ParamDict pd;
  1539. innerproduct2->load_param(pd);
  1540. innerproduct2->num_output = convolution->num_output;
  1541. innerproduct2->bias_term = convolution->bias_term;
  1542. innerproduct2->weight_data_size = convolution->weight_data_size;
  1543. innerproduct->int8_scale_term = convolution->int8_scale_term;
  1544. innerproduct2->weight_data = convolution->weight_data;
  1545. innerproduct2->bias_data = convolution->bias_data;
  1546. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  1547. innerproduct->bottom_blob_int8_scale = convolution->bottom_blob_int8_scale;
  1548. innerproduct2->activation_type = convolution->activation_type;
  1549. innerproduct2->activation_params = convolution->activation_params;
  1550. layers[j] = innerproduct2;
  1551. delete convolution;
  1552. replaced = true;
  1553. }
  1554. if (!replaced)
  1555. break;
  1556. }
  1557. return 0;
  1558. }
  1559. int NetOptimize::shape_inference()
  1560. {
  1561. const size_t layer_count = layers.size();
  1562. const size_t blob_count = blobs.size();
  1563. ncnn::Extractor ex = create_extractor();
  1564. // prepare Input blobs
  1565. for (size_t i=0; i<layer_count; i++)
  1566. {
  1567. const ncnn::Layer* layer = layers[i];
  1568. if (layer->type == "ncnnfused")
  1569. continue;
  1570. if (layer->type != "Input")
  1571. continue;
  1572. ncnn::Input* input = (ncnn::Input*)layer;
  1573. int w = input->w;
  1574. int h = input->h;
  1575. int c = input->c;
  1576. int dims = 0;
  1577. if (w == 0 && h == 0 && c == 0) dims = 0;
  1578. if (w != 0 && h == 0 && c == 0) dims = 1;
  1579. if (w != 0 && h != 0 && c == 0) dims = 2;
  1580. if (w != 0 && h != 0 && c != 0) dims = 3;
  1581. if (dims == 0)
  1582. {
  1583. fprintf(stderr, "Input layer %s without shape info, shape_inference aborted\n", layer->name.c_str());
  1584. return -1;
  1585. }
  1586. ncnn::Mat m;
  1587. if (dims == 1) m.create(w);
  1588. if (dims == 2) m.create(w, h);
  1589. if (dims == 3) m.create(w, h, c);
  1590. ex.input(layer->tops[0], m);
  1591. }
  1592. // prepare blobs with predefined shape
  1593. for (size_t i=0; i<blob_count; i++)
  1594. {
  1595. const ncnn::Blob blob = blobs[i];
  1596. int dims = blob.shape.dims;
  1597. int w = blob.shape.w;
  1598. int h = blob.shape.h;
  1599. int c = blob.shape.c;
  1600. if (dims == 0)
  1601. continue;
  1602. ncnn::Mat m;
  1603. if (dims == 1) m.create(w);
  1604. if (dims == 2) m.create(w, h);
  1605. if (dims == 3) m.create(w, h, c);
  1606. ex.input(int(i), m);
  1607. }
  1608. fprintf(stderr, "shape_inference\n");
  1609. // resolve all layer output blob shape
  1610. for (size_t i=0; i<layer_count; i++)
  1611. {
  1612. const ncnn::Layer* layer = layers[i];
  1613. if (layer->type == "ncnnfused")
  1614. continue;
  1615. for (size_t j=0; j<layer->tops.size(); j++)
  1616. {
  1617. int top_blob_index = layer->tops[j];
  1618. ncnn::Mat m;
  1619. ex.extract(top_blob_index, m);
  1620. blobs[top_blob_index].shape = m;
  1621. }
  1622. }
  1623. // assign all layer blob shape
  1624. for (size_t i=0; i<layer_count; i++)
  1625. {
  1626. ncnn::Layer* layer = layers[i];
  1627. if (layer->type == "ncnnfused")
  1628. continue;
  1629. layer->bottom_shapes.resize(layer->bottoms.size());
  1630. for (size_t j=0; j<layer->bottoms.size(); j++)
  1631. {
  1632. int bottom_blob_index = layer->bottoms[j];
  1633. layer->bottom_shapes[j] = blobs[bottom_blob_index].shape;
  1634. }
  1635. layer->top_shapes.resize(layer->tops.size());
  1636. for (size_t j=0; j<layer->tops.size(); j++)
  1637. {
  1638. int top_blob_index = layer->tops[j];
  1639. layer->top_shapes[j] = blobs[top_blob_index].shape;
  1640. // 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());
  1641. }
  1642. }
  1643. return 0;
  1644. }
  1645. int NetOptimize::fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp)
  1646. {
  1647. const int count = m.w;
  1648. const int* ptr = m;
  1649. fprintf(pp, " -%d=%d", 23300 + id, count);
  1650. for (int i=0; i<count; i++)
  1651. {
  1652. fprintf(pp, ",%d", ptr[i]);
  1653. }
  1654. return 0;
  1655. }
  1656. int NetOptimize::fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp)
  1657. {
  1658. const int count = m.w;
  1659. const float* ptr = m;
  1660. fprintf(pp, " -%d=%d", 23300 + id, count);
  1661. for (int i=0; i<count; i++)
  1662. {
  1663. fprintf(pp, ",%e", ptr[i]);
  1664. }
  1665. return 0;
  1666. }
  1667. static inline size_t alignSize(size_t sz, int n)
  1668. {
  1669. return (sz + n-1) & -n;
  1670. }
  1671. int NetOptimize::fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp)
  1672. {
  1673. int p0 = ftell(bp);
  1674. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  1675. if (storage_type == 1 && tag == 0)
  1676. {
  1677. tag = 0x01306B47; // fp16 magic
  1678. fwrite(&tag, sizeof(int), 1, bp);
  1679. ncnn::Mat data_flattened_fp16;
  1680. ncnn::cast_float32_to_float16(data_flattened, data_flattened_fp16);
  1681. fwrite(data_flattened_fp16.data, data_flattened_fp16.elemsize, data_flattened_fp16.w, bp);
  1682. }
  1683. else
  1684. {
  1685. fwrite(&tag, sizeof(int), 1, bp);
  1686. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  1687. }
  1688. // padding to 32bit align
  1689. int nwrite = ftell(bp) - p0;
  1690. size_t nalign = alignSize(nwrite, 4);
  1691. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  1692. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  1693. return 0;
  1694. }
  1695. int NetOptimize::fwrite_weight_data(const ncnn::Mat& data, FILE* bp)
  1696. {
  1697. int p0 = ftell(bp);
  1698. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  1699. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  1700. // padding to 32bit align
  1701. int nwrite = ftell(bp) - p0;
  1702. size_t nalign = alignSize(nwrite, 4);
  1703. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  1704. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  1705. return 0;
  1706. }
  1707. int NetOptimize::save(const char* parampath, const char* binpath)
  1708. {
  1709. FILE* pp = fopen(parampath, "wb");
  1710. FILE* bp = fopen(binpath, "wb");
  1711. fprintf(pp, "7767517\n");
  1712. const size_t layer_count = layers.size();
  1713. int layer_count_fused = 0;
  1714. std::set<std::string> blob_names;
  1715. for (int i=0; i<layer_count; i++)
  1716. {
  1717. const ncnn::Layer* layer = layers[i];
  1718. if (layer->type == "ncnnfused")
  1719. continue;
  1720. layer_count_fused++;
  1721. size_t bottom_count = layer->bottoms.size();
  1722. for (int j=0; j<bottom_count; j++)
  1723. {
  1724. int bottom_blob_index = layer->bottoms[j];
  1725. blob_names.insert(blobs[bottom_blob_index].name);
  1726. }
  1727. size_t top_count = layer->tops.size();
  1728. for (int j=0; j<top_count; j++)
  1729. {
  1730. int top_blob_index = layer->tops[j];
  1731. blob_names.insert(blobs[top_blob_index].name);
  1732. }
  1733. }
  1734. size_t blob_count_fused = blob_names.size();
  1735. fprintf(pp, "%d %zd\n", layer_count_fused, blob_count_fused);
  1736. for (int i=0; i<layer_count; i++)
  1737. {
  1738. const ncnn::Layer* layer = layers[i];
  1739. if (layer->type == "ncnnfused")
  1740. continue;
  1741. size_t bottom_count = layer->bottoms.size();
  1742. size_t top_count = layer->tops.size();
  1743. fprintf(pp, "%-24s %-24s %zd %zd", layer->type.c_str(), layer->name.c_str(), bottom_count, top_count);
  1744. for (int j=0; j<bottom_count; j++)
  1745. {
  1746. int bottom_blob_index = layer->bottoms[j];
  1747. fprintf(pp, " %s", blobs[bottom_blob_index].name.c_str());
  1748. }
  1749. for (int j=0; j<top_count; j++)
  1750. {
  1751. int top_blob_index = layer->tops[j];
  1752. fprintf(pp, " %s", blobs[top_blob_index].name.c_str());
  1753. }
  1754. // write shape hints
  1755. bool shape_ready = true;
  1756. for (int j=0; j<top_count; j++)
  1757. {
  1758. int top_blob_index = layer->tops[j];
  1759. int dims = blobs[top_blob_index].shape.dims;
  1760. if (dims == 0)
  1761. {
  1762. shape_ready = false;
  1763. break;
  1764. }
  1765. }
  1766. if (shape_ready)
  1767. {
  1768. fprintf(pp, " -23330=%zd", top_count * 4);
  1769. for (int j=0; j<top_count; j++)
  1770. {
  1771. int top_blob_index = layer->tops[j];
  1772. int dims = blobs[top_blob_index].shape.dims;
  1773. int w = blobs[top_blob_index].shape.w;
  1774. int h = blobs[top_blob_index].shape.h;
  1775. int c = blobs[top_blob_index].shape.c;
  1776. fprintf(pp, ",%d,%d,%d,%d", dims, w, h, c);
  1777. }
  1778. }
  1779. ncnn::Layer* layer_default = ncnn::create_layer(layer->typeindex);
  1780. ncnn::ParamDict pd;
  1781. layer_default->load_param(pd);
  1782. #define fprintf_param_value(format, phase) \
  1783. { if (op->phase != op_default->phase) fprintf(pp, format, op->phase); }
  1784. if (layer->type == "BatchNorm")
  1785. {
  1786. ncnn::BatchNorm* op = (ncnn::BatchNorm*)layer;
  1787. ncnn::BatchNorm* op_default = (ncnn::BatchNorm*)layer_default;
  1788. fprintf_param_value(" 0=%d", channels)
  1789. fprintf_param_value(" 1=%e", eps)
  1790. fwrite_weight_data(op->slope_data, bp);
  1791. fwrite_weight_data(op->mean_data, bp);
  1792. fwrite_weight_data(op->var_data, bp);
  1793. fwrite_weight_data(op->bias_data, bp);
  1794. }
  1795. else if (layer->type == "Bias")
  1796. {
  1797. ncnn::Bias* op = (ncnn::Bias*)layer;
  1798. ncnn::Bias* op_default = (ncnn::Bias*)layer_default;
  1799. fprintf_param_value(" 0=%d", bias_data_size)
  1800. fwrite_weight_data(op->bias_data, bp);
  1801. }
  1802. else if (layer->type == "BinaryOp")
  1803. {
  1804. ncnn::BinaryOp* op = (ncnn::BinaryOp*)layer;
  1805. ncnn::BinaryOp* op_default = (ncnn::BinaryOp*)layer_default;
  1806. fprintf_param_value(" 0=%d", op_type)
  1807. fprintf_param_value(" 1=%d", with_scalar)
  1808. fprintf_param_value(" 2=%e", b)
  1809. }
  1810. else if (layer->type == "Clip")
  1811. {
  1812. ncnn::Clip* op = (ncnn::Clip*)layer;
  1813. ncnn::Clip* op_default = (ncnn::Clip*)layer_default;
  1814. fprintf_param_value(" 0=%e", min)
  1815. fprintf_param_value(" 1=%e", max)
  1816. }
  1817. else if (layer->type == "Concat")
  1818. {
  1819. ncnn::Concat* op = (ncnn::Concat*)layer;
  1820. ncnn::Concat* op_default = (ncnn::Concat*)layer_default;
  1821. fprintf_param_value(" 0=%d", axis)
  1822. }
  1823. else if (layer->type == "Convolution")
  1824. {
  1825. ncnn::Convolution* op = (ncnn::Convolution*)layer;
  1826. ncnn::Convolution* op_default = (ncnn::Convolution*)layer_default;
  1827. fprintf_param_value(" 0=%d", num_output)
  1828. fprintf_param_value(" 1=%d", kernel_w)
  1829. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1830. fprintf_param_value(" 2=%d", dilation_w)
  1831. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1832. fprintf_param_value(" 3=%d", stride_w)
  1833. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1834. fprintf_param_value(" 4=%d", pad_left)
  1835. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1836. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1837. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1838. fprintf_param_value(" 18=%e", pad_value)
  1839. fprintf_param_value(" 5=%d", bias_term)
  1840. fprintf_param_value(" 6=%d", weight_data_size)
  1841. fprintf_param_value(" 8=%d", int8_scale_term)
  1842. fprintf_param_value(" 9=%d", activation_type)
  1843. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1844. fprintf_param_value(" 17=%d", impl_type)
  1845. fwrite_weight_tag_data(0, op->weight_data, bp);
  1846. fwrite_weight_data(op->bias_data, bp);
  1847. }
  1848. else if (layer->type == "ConvolutionDepthWise")
  1849. {
  1850. ncnn::ConvolutionDepthWise* op = (ncnn::ConvolutionDepthWise*)layer;
  1851. ncnn::ConvolutionDepthWise* op_default = (ncnn::ConvolutionDepthWise*)layer_default;
  1852. fprintf_param_value(" 0=%d", num_output)
  1853. fprintf_param_value(" 1=%d", kernel_w)
  1854. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1855. fprintf_param_value(" 2=%d", dilation_w)
  1856. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1857. fprintf_param_value(" 3=%d", stride_w)
  1858. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1859. fprintf_param_value(" 4=%d", pad_left)
  1860. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1861. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1862. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1863. fprintf_param_value(" 18=%e", pad_value)
  1864. fprintf_param_value(" 5=%d", bias_term)
  1865. fprintf_param_value(" 6=%d", weight_data_size)
  1866. fprintf_param_value(" 7=%d", group)
  1867. fprintf_param_value(" 8=%d", int8_scale_term)
  1868. fprintf_param_value(" 9=%d", activation_type)
  1869. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1870. fwrite_weight_tag_data(0, op->weight_data, bp);
  1871. fwrite_weight_data(op->bias_data, bp);
  1872. }
  1873. else if (layer->type == "Crop")
  1874. {
  1875. ncnn::Crop* op = (ncnn::Crop*)layer;
  1876. ncnn::Crop* op_default = (ncnn::Crop*)layer_default;
  1877. fprintf_param_value(" 0=%d", woffset)
  1878. fprintf_param_value(" 1=%d", hoffset)
  1879. fprintf_param_value(" 2=%d", coffset)
  1880. fprintf_param_value(" 3=%d", outw)
  1881. fprintf_param_value(" 4=%d", outh)
  1882. fprintf_param_value(" 5=%d", outc)
  1883. fprintf_param_value(" 6=%d", woffset2)
  1884. fprintf_param_value(" 7=%d", hoffset2)
  1885. fprintf_param_value(" 8=%d", coffset2)
  1886. { if (!op->starts.empty()) fprintf_param_int_array(9, op->starts, pp); }
  1887. { if (!op->ends.empty()) fprintf_param_int_array(10, op->ends, pp); }
  1888. { if (!op->axes.empty()) fprintf_param_int_array(11, op->axes, pp); }
  1889. }
  1890. else if (layer->type == "Deconvolution")
  1891. {
  1892. ncnn::Deconvolution* op = (ncnn::Deconvolution*)layer;
  1893. ncnn::Deconvolution* op_default = (ncnn::Deconvolution*)layer_default;
  1894. fprintf_param_value(" 0=%d", num_output)
  1895. fprintf_param_value(" 1=%d", kernel_w)
  1896. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1897. fprintf_param_value(" 2=%d", dilation_w)
  1898. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1899. fprintf_param_value(" 3=%d", stride_w)
  1900. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1901. fprintf_param_value(" 4=%d", pad_left)
  1902. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1903. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1904. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1905. fprintf_param_value(" 18=%d", output_pad_right)
  1906. { if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom); }
  1907. fprintf_param_value(" 20=%d", output_w)
  1908. { if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h); }
  1909. fprintf_param_value(" 5=%d", bias_term)
  1910. fprintf_param_value(" 6=%d", weight_data_size)
  1911. fprintf_param_value(" 9=%d", activation_type)
  1912. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1913. fwrite_weight_tag_data(0, op->weight_data, bp);
  1914. fwrite_weight_data(op->bias_data, bp);
  1915. }
  1916. else if (layer->type == "DeconvolutionDepthWise")
  1917. {
  1918. ncnn::DeconvolutionDepthWise* op = (ncnn::DeconvolutionDepthWise*)layer;
  1919. ncnn::DeconvolutionDepthWise* op_default = (ncnn::DeconvolutionDepthWise*)layer_default;
  1920. fprintf_param_value(" 0=%d", num_output)
  1921. fprintf_param_value(" 1=%d", kernel_w)
  1922. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1923. fprintf_param_value(" 2=%d", dilation_w)
  1924. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1925. fprintf_param_value(" 3=%d", stride_w)
  1926. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1927. fprintf_param_value(" 4=%d", pad_left)
  1928. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1929. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1930. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1931. fprintf_param_value(" 18=%d", output_pad_right)
  1932. { if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom); }
  1933. fprintf_param_value(" 20=%d", output_w)
  1934. { if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h); }
  1935. fprintf_param_value(" 5=%d", bias_term)
  1936. fprintf_param_value(" 6=%d", weight_data_size)
  1937. fprintf_param_value(" 7=%d", group)
  1938. fprintf_param_value(" 9=%d", activation_type)
  1939. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1940. fwrite_weight_tag_data(0, op->weight_data, bp);
  1941. fwrite_weight_data(op->bias_data, bp);
  1942. }
  1943. else if (layer->type == "DetectionOutput")
  1944. {
  1945. ncnn::DetectionOutput* op = (ncnn::DetectionOutput*)layer;
  1946. ncnn::DetectionOutput* op_default = (ncnn::DetectionOutput*)layer_default;
  1947. fprintf_param_value(" 0=%d", num_class)
  1948. fprintf_param_value(" 1=%e", nms_threshold)
  1949. fprintf_param_value(" 2=%d", nms_top_k)
  1950. fprintf_param_value(" 3=%d", keep_top_k)
  1951. fprintf_param_value(" 4=%e", confidence_threshold)
  1952. fprintf_param_value(" 5=%e", variances[0])
  1953. fprintf_param_value(" 6=%e", variances[1])
  1954. fprintf_param_value(" 7=%e", variances[2])
  1955. fprintf_param_value(" 8=%e", variances[3])
  1956. }
  1957. else if (layer->type == "Dropout")
  1958. {
  1959. ncnn::Dropout* op = (ncnn::Dropout*)layer;
  1960. ncnn::Dropout* op_default = (ncnn::Dropout*)layer_default;
  1961. fprintf_param_value(" 0=%e", scale)
  1962. }
  1963. else if (layer->type == "Eltwise")
  1964. {
  1965. ncnn::Eltwise* op = (ncnn::Eltwise*)layer;
  1966. ncnn::Eltwise* op_default = (ncnn::Eltwise*)layer_default;
  1967. fprintf_param_value(" 0=%d", op_type)
  1968. { if (!op->coeffs.empty()) fprintf_param_float_array(1, op->coeffs, pp); }
  1969. }
  1970. else if (layer->type == "ELU")
  1971. {
  1972. ncnn::ELU* op = (ncnn::ELU*)layer;
  1973. ncnn::ELU* op_default = (ncnn::ELU*)layer_default;
  1974. fprintf_param_value(" 0=%e", alpha)
  1975. }
  1976. else if (layer->type == "Exp")
  1977. {
  1978. ncnn::Exp* op = (ncnn::Exp*)layer;
  1979. ncnn::Exp* op_default = (ncnn::Exp*)layer_default;
  1980. fprintf_param_value(" 0=%e", base)
  1981. fprintf_param_value(" 1=%e", scale)
  1982. fprintf_param_value(" 2=%e", shift)
  1983. }
  1984. else if (layer->type == "ExpandDims")
  1985. {
  1986. ncnn::ExpandDims* op = (ncnn::ExpandDims*)layer;
  1987. ncnn::ExpandDims* op_default = (ncnn::ExpandDims*)layer_default;
  1988. fprintf_param_value(" 0=%d", expand_w)
  1989. fprintf_param_value(" 1=%d", expand_h)
  1990. fprintf_param_value(" 2=%d", expand_c)
  1991. { if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp); }
  1992. }
  1993. else if (layer->type == "HardSigmoid")
  1994. {
  1995. ncnn::HardSigmoid* op = (ncnn::HardSigmoid*)layer;
  1996. ncnn::HardSigmoid* op_default = (ncnn::HardSigmoid*)layer_default;
  1997. fprintf_param_value(" 0=%e", alpha)
  1998. fprintf_param_value(" 1=%e", beta)
  1999. }
  2000. else if (layer->type == "HardSwish")
  2001. {
  2002. ncnn::HardSwish* op = (ncnn::HardSwish*)layer;
  2003. ncnn::HardSwish* op_default = (ncnn::HardSwish*)layer_default;
  2004. fprintf_param_value(" 0=%e", alpha)
  2005. fprintf_param_value(" 1=%e", beta)
  2006. }
  2007. else if (layer->type == "InnerProduct")
  2008. {
  2009. ncnn::InnerProduct* op = (ncnn::InnerProduct*)layer;
  2010. ncnn::InnerProduct* op_default = (ncnn::InnerProduct*)layer_default;
  2011. fprintf_param_value(" 0=%d", num_output)
  2012. fprintf_param_value(" 1=%d", bias_term)
  2013. fprintf_param_value(" 2=%d", weight_data_size)
  2014. fprintf_param_value(" 8=%d", int8_scale_term)
  2015. fprintf_param_value(" 9=%d", activation_type)
  2016. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  2017. fwrite_weight_tag_data(0, op->weight_data, bp);
  2018. fwrite_weight_data(op->bias_data, bp);
  2019. }
  2020. else if (layer->type == "Input")
  2021. {
  2022. ncnn::Input* op = (ncnn::Input*)layer;
  2023. ncnn::Input* op_default = (ncnn::Input*)layer_default;
  2024. fprintf_param_value(" 0=%d", w)
  2025. fprintf_param_value(" 1=%d", h)
  2026. fprintf_param_value(" 2=%d", c)
  2027. }
  2028. else if (layer->type == "InstanceNorm")
  2029. {
  2030. ncnn::InstanceNorm* op = (ncnn::InstanceNorm*)layer;
  2031. ncnn::InstanceNorm* op_default = (ncnn::InstanceNorm*)layer_default;
  2032. fprintf_param_value(" 0=%d", channels)
  2033. fprintf_param_value(" 1=%e", eps)
  2034. fwrite_weight_data(op->gamma_data, bp);
  2035. fwrite_weight_data(op->beta_data, bp);
  2036. }
  2037. else if (layer->type == "Interp")
  2038. {
  2039. ncnn::Interp* op = (ncnn::Interp*)layer;
  2040. ncnn::Interp* op_default = (ncnn::Interp*)layer_default;
  2041. fprintf_param_value(" 0=%d", resize_type)
  2042. fprintf_param_value(" 1=%e", height_scale)
  2043. fprintf_param_value(" 2=%e", width_scale)
  2044. fprintf_param_value(" 3=%d", output_height)
  2045. fprintf_param_value(" 4=%d", output_width)
  2046. }
  2047. else if (layer->type == "Log")
  2048. {
  2049. ncnn::Log* op = (ncnn::Log*)layer;
  2050. ncnn::Log* op_default = (ncnn::Log*)layer_default;
  2051. fprintf_param_value(" 0=%e", base)
  2052. fprintf_param_value(" 1=%e", scale)
  2053. fprintf_param_value(" 2=%e", shift)
  2054. }
  2055. else if (layer->type == "LRN")
  2056. {
  2057. ncnn::LRN* op = (ncnn::LRN*)layer;
  2058. ncnn::LRN* op_default = (ncnn::LRN*)layer_default;
  2059. fprintf_param_value(" 0=%d", region_type)
  2060. fprintf_param_value(" 1=%d", local_size)
  2061. fprintf_param_value(" 2=%e", alpha)
  2062. fprintf_param_value(" 3=%e", beta)
  2063. fprintf_param_value(" 4=%e", bias)
  2064. }
  2065. else if (layer->type == "LSTM")
  2066. {
  2067. ncnn::LSTM* op = (ncnn::LSTM*)layer;
  2068. ncnn::LSTM* op_default = (ncnn::LSTM*)layer_default;
  2069. fprintf_param_value(" 0=%d", num_output)
  2070. fprintf_param_value(" 1=%d", weight_data_size)
  2071. fprintf_param_value(" 2=%d", direction)
  2072. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  2073. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  2074. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  2075. }
  2076. else if (layer->type == "MemoryData")
  2077. {
  2078. ncnn::MemoryData* op = (ncnn::MemoryData*)layer;
  2079. ncnn::MemoryData* op_default = (ncnn::MemoryData*)layer_default;
  2080. fprintf_param_value(" 0=%d", w)
  2081. fprintf_param_value(" 1=%d", h)
  2082. fprintf_param_value(" 2=%d", c)
  2083. fwrite_weight_data(op->data, bp);
  2084. }
  2085. else if (layer->type == "MVN")
  2086. {
  2087. ncnn::MVN* op = (ncnn::MVN*)layer;
  2088. ncnn::MVN* op_default = (ncnn::MVN*)layer_default;
  2089. fprintf_param_value(" 0=%d", normalize_variance)
  2090. fprintf_param_value(" 1=%d", across_channels)
  2091. fprintf_param_value(" 2=%e", eps)
  2092. }
  2093. else if (layer->type == "Normalize")
  2094. {
  2095. ncnn::Normalize* op = (ncnn::Normalize*)layer;
  2096. ncnn::Normalize* op_default = (ncnn::Normalize*)layer_default;
  2097. fprintf_param_value(" 0=%d", across_spatial)
  2098. fprintf_param_value(" 1=%d", channel_shared)
  2099. fprintf_param_value(" 2=%e", eps)
  2100. fprintf_param_value(" 3=%d", scale_data_size)
  2101. fprintf_param_value(" 4=%d", across_channel)
  2102. fprintf_param_value(" 9=%d", eps_mode)
  2103. fwrite_weight_data(op->scale_data, bp);
  2104. }
  2105. else if (layer->type == "Padding")
  2106. {
  2107. ncnn::Padding* op = (ncnn::Padding*)layer;
  2108. ncnn::Padding* op_default = (ncnn::Padding*)layer_default;
  2109. fprintf_param_value(" 0=%d", top)
  2110. fprintf_param_value(" 1=%d", bottom)
  2111. fprintf_param_value(" 2=%d", left)
  2112. fprintf_param_value(" 3=%d", right)
  2113. fprintf_param_value(" 4=%d", type)
  2114. fprintf_param_value(" 5=%e", value)
  2115. }
  2116. else if (layer->type == "Permute")
  2117. {
  2118. ncnn::Permute* op = (ncnn::Permute*)layer;
  2119. ncnn::Permute* op_default = (ncnn::Permute*)layer_default;
  2120. fprintf_param_value(" 0=%d", order_type)
  2121. }
  2122. else if (layer->type == "PixelShuffle")
  2123. {
  2124. ncnn::PixelShuffle* op = (ncnn::PixelShuffle*)layer;
  2125. ncnn::PixelShuffle* op_default = (ncnn::PixelShuffle*)layer_default;
  2126. fprintf_param_value(" 0=%d", upscale_factor)
  2127. }
  2128. else if (layer->type == "Pooling")
  2129. {
  2130. ncnn::Pooling* op = (ncnn::Pooling*)layer;
  2131. ncnn::Pooling* op_default = (ncnn::Pooling*)layer_default;
  2132. fprintf_param_value(" 0=%d", pooling_type)
  2133. fprintf_param_value(" 1=%d", kernel_w)
  2134. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  2135. fprintf_param_value(" 2=%d", stride_w)
  2136. { if (op->stride_h != op->stride_w) fprintf(pp, " 12=%d", op->stride_h); }
  2137. fprintf_param_value(" 3=%d", pad_left)
  2138. { if (op->pad_top != op->pad_left) fprintf(pp, " 13=%d", op->pad_top); }
  2139. { if (op->pad_right != op->pad_left) fprintf(pp, " 14=%d", op->pad_right); }
  2140. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 15=%d", op->pad_bottom); }
  2141. fprintf_param_value(" 4=%d", global_pooling)
  2142. fprintf_param_value(" 5=%d", pad_mode)
  2143. }
  2144. else if (layer->type == "Power")
  2145. {
  2146. ncnn::Power* op = (ncnn::Power*)layer;
  2147. ncnn::Power* op_default = (ncnn::Power*)layer_default;
  2148. fprintf_param_value(" 0=%e", power)
  2149. fprintf_param_value(" 1=%e", scale)
  2150. fprintf_param_value(" 2=%e", shift)
  2151. }
  2152. else if (layer->type == "PReLU")
  2153. {
  2154. ncnn::PReLU* op = (ncnn::PReLU*)layer;
  2155. ncnn::PReLU* op_default = (ncnn::PReLU*)layer_default;
  2156. fprintf_param_value(" 0=%d", num_slope)
  2157. fwrite_weight_data(op->slope_data, bp);
  2158. }
  2159. else if (layer->type == "PriorBox")
  2160. {
  2161. ncnn::PriorBox* op = (ncnn::PriorBox*)layer;
  2162. ncnn::PriorBox* op_default = (ncnn::PriorBox*)layer_default;
  2163. { if (!op->min_sizes.empty()) fprintf_param_float_array(0, op->min_sizes, pp); }
  2164. { if (!op->max_sizes.empty()) fprintf_param_float_array(1, op->max_sizes, pp); }
  2165. { if (!op->aspect_ratios.empty()) fprintf_param_float_array(2, op->aspect_ratios, pp); }
  2166. fprintf_param_value(" 3=%e", variances[0])
  2167. fprintf_param_value(" 4=%e", variances[1])
  2168. fprintf_param_value(" 5=%e", variances[2])
  2169. fprintf_param_value(" 6=%e", variances[3])
  2170. fprintf_param_value(" 7=%d", flip)
  2171. fprintf_param_value(" 8=%d", clip)
  2172. fprintf_param_value(" 9=%d", image_width)
  2173. fprintf_param_value(" 10=%d", image_height)
  2174. fprintf_param_value(" 11=%e", step_width)
  2175. fprintf_param_value(" 12=%e", step_height)
  2176. fprintf_param_value(" 13=%e", offset)
  2177. }
  2178. else if (layer->type == "Proposal")
  2179. {
  2180. ncnn::Proposal* op = (ncnn::Proposal*)layer;
  2181. ncnn::Proposal* op_default = (ncnn::Proposal*)layer_default;
  2182. fprintf_param_value(" 0=%d", feat_stride)
  2183. fprintf_param_value(" 1=%d", base_size)
  2184. fprintf_param_value(" 2=%d", pre_nms_topN)
  2185. fprintf_param_value(" 3=%d", after_nms_topN)
  2186. fprintf_param_value(" 4=%e", nms_thresh)
  2187. fprintf_param_value(" 5=%d", min_size)
  2188. }
  2189. else if (layer->type == "PSROIPooling")
  2190. {
  2191. ncnn::PSROIPooling* op = (ncnn::PSROIPooling*)layer;
  2192. ncnn::PSROIPooling* op_default = (ncnn::PSROIPooling*)layer_default;
  2193. fprintf_param_value(" 0=%d", pooled_width)
  2194. fprintf_param_value(" 1=%d", pooled_height)
  2195. fprintf_param_value(" 2=%e", spatial_scale)
  2196. fprintf_param_value(" 3=%d", output_dim)
  2197. }
  2198. else if (layer->type == "Quantize")
  2199. {
  2200. ncnn::Quantize* op = (ncnn::Quantize*)layer;
  2201. ncnn::Quantize* op_default = (ncnn::Quantize*)layer_default;
  2202. fprintf_param_value(" 0=%e", scale)
  2203. }
  2204. else if (layer->type == "Reduction")
  2205. {
  2206. ncnn::Reduction* op = (ncnn::Reduction*)layer;
  2207. ncnn::Reduction* op_default = (ncnn::Reduction*)layer_default;
  2208. fprintf_param_value(" 0=%d", operation)
  2209. fprintf_param_value(" 1=%d", reduce_all)
  2210. fprintf_param_value(" 2=%e", coeff)
  2211. { if (!op->axes.empty()) fprintf_param_int_array(3, op->axes, pp); }
  2212. fprintf_param_value(" 4=%d", keepdims)
  2213. }
  2214. else if (layer->type == "ReLU")
  2215. {
  2216. ncnn::ReLU* op = (ncnn::ReLU*)layer;
  2217. ncnn::ReLU* op_default = (ncnn::ReLU*)layer_default;
  2218. fprintf_param_value(" 0=%e", slope)
  2219. }
  2220. else if (layer->type == "Reorg")
  2221. {
  2222. ncnn::Reorg* op = (ncnn::Reorg*)layer;
  2223. ncnn::Reorg* op_default = (ncnn::Reorg*)layer_default;
  2224. fprintf_param_value(" 0=%d", stride)
  2225. }
  2226. else if (layer->type == "Requantize")
  2227. {
  2228. ncnn::Requantize* op = (ncnn::Requantize*)layer;
  2229. ncnn::Requantize* op_default = (ncnn::Requantize*)layer_default;
  2230. fprintf_param_value(" 0=%e", scale_in)
  2231. fprintf_param_value(" 1=%e", scale_out)
  2232. fprintf_param_value(" 2=%d", bias_term)
  2233. fprintf_param_value(" 3=%d", bias_data_size)
  2234. fprintf_param_value(" 4=%d", fusion_relu)
  2235. }
  2236. else if (layer->type == "Reshape")
  2237. {
  2238. ncnn::Reshape* op = (ncnn::Reshape*)layer;
  2239. ncnn::Reshape* op_default = (ncnn::Reshape*)layer_default;
  2240. fprintf_param_value(" 0=%d", w)
  2241. fprintf_param_value(" 1=%d", h)
  2242. fprintf_param_value(" 2=%d", c)
  2243. fprintf_param_value(" 3=%d", permute)
  2244. }
  2245. else if (layer->type == "ROIAlign")
  2246. {
  2247. ncnn::ROIAlign* op = (ncnn::ROIAlign*)layer;
  2248. ncnn::ROIAlign* op_default = (ncnn::ROIAlign*)layer_default;
  2249. fprintf_param_value(" 0=%d", pooled_width)
  2250. fprintf_param_value(" 1=%d", pooled_height)
  2251. fprintf_param_value(" 2=%e", spatial_scale)
  2252. }
  2253. else if (layer->type == "ROIPooling")
  2254. {
  2255. ncnn::ROIPooling* op = (ncnn::ROIPooling*)layer;
  2256. ncnn::ROIPooling* op_default = (ncnn::ROIPooling*)layer_default;
  2257. fprintf_param_value(" 0=%d", pooled_width)
  2258. fprintf_param_value(" 1=%d", pooled_height)
  2259. fprintf_param_value(" 2=%e", spatial_scale)
  2260. }
  2261. else if (layer->type == "Scale")
  2262. {
  2263. ncnn::Scale* op = (ncnn::Scale*)layer;
  2264. ncnn::Scale* op_default = (ncnn::Scale*)layer_default;
  2265. fprintf_param_value(" 0=%d", scale_data_size)
  2266. fprintf_param_value(" 1=%d", bias_term)
  2267. fwrite_weight_data(op->scale_data, bp);
  2268. fwrite_weight_data(op->bias_data, bp);
  2269. }
  2270. else if (layer->type == "ShuffleChannel")
  2271. {
  2272. ncnn::ShuffleChannel* op = (ncnn::ShuffleChannel*)layer;
  2273. ncnn::ShuffleChannel* op_default = (ncnn::ShuffleChannel*)layer_default;
  2274. fprintf_param_value(" 0=%d", group)
  2275. }
  2276. else if (layer->type == "Slice")
  2277. {
  2278. ncnn::Slice* op = (ncnn::Slice*)layer;
  2279. ncnn::Slice* op_default = (ncnn::Slice*)layer_default;
  2280. { if (!op->slices.empty()) fprintf_param_int_array(0, op->slices, pp); }
  2281. fprintf_param_value(" 1=%d", axis)
  2282. }
  2283. else if (layer->type == "Softmax")
  2284. {
  2285. ncnn::Softmax* op = (ncnn::Softmax*)layer;
  2286. ncnn::Softmax* op_default = (ncnn::Softmax*)layer_default;
  2287. fprintf_param_value(" 0=%d", axis)
  2288. // HACK
  2289. if (op->axis != 0)
  2290. {
  2291. int fixbug0 = 1;
  2292. fprintf(pp, " 1=%d", fixbug0);
  2293. }
  2294. }
  2295. else if (layer->type == "Squeeze")
  2296. {
  2297. ncnn::Squeeze* op = (ncnn::Squeeze*)layer;
  2298. ncnn::Squeeze* op_default = (ncnn::Squeeze*)layer_default;
  2299. fprintf_param_value(" 0=%d", squeeze_w)
  2300. fprintf_param_value(" 1=%d", squeeze_h)
  2301. fprintf_param_value(" 2=%d", squeeze_c)
  2302. { if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp); }
  2303. }
  2304. else if (layer->type == "Threshold")
  2305. {
  2306. ncnn::Threshold* op = (ncnn::Threshold*)layer;
  2307. ncnn::Threshold* op_default = (ncnn::Threshold*)layer_default;
  2308. fprintf_param_value(" 0=%e", threshold)
  2309. }
  2310. else if (layer->type == "UnaryOp")
  2311. {
  2312. ncnn::UnaryOp* op = (ncnn::UnaryOp*)layer;
  2313. ncnn::UnaryOp* op_default = (ncnn::UnaryOp*)layer_default;
  2314. fprintf_param_value(" 0=%d", op_type)
  2315. }
  2316. else if (layer->type == "YoloDetectionOutput")
  2317. {
  2318. ncnn::YoloDetectionOutput* op = (ncnn::YoloDetectionOutput*)layer;
  2319. ncnn::YoloDetectionOutput* op_default = (ncnn::YoloDetectionOutput*)layer_default;
  2320. fprintf_param_value(" 0=%d", num_class)
  2321. fprintf_param_value(" 1=%d", num_box)
  2322. fprintf_param_value(" 2=%e", confidence_threshold)
  2323. fprintf_param_value(" 3=%e", nms_threshold)
  2324. { if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp); }
  2325. }
  2326. else if (layer->type == "Yolov3DetectionOutput")
  2327. {
  2328. ncnn::Yolov3DetectionOutput* op = (ncnn::Yolov3DetectionOutput*)layer;
  2329. ncnn::Yolov3DetectionOutput* op_default = (ncnn::Yolov3DetectionOutput*)layer_default;
  2330. fprintf_param_value(" 0=%d", num_class)
  2331. fprintf_param_value(" 1=%d", num_box)
  2332. fprintf_param_value(" 2=%e", confidence_threshold)
  2333. fprintf_param_value(" 3=%e", nms_threshold)
  2334. { if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp); }
  2335. { if (!op->mask.empty()) fprintf_param_int_array(5, op->mask, pp); }
  2336. { if (!op->anchors_scale.empty()) fprintf_param_float_array(6, op->anchors_scale, pp); }
  2337. }
  2338. #undef fprintf_param_value
  2339. fprintf(pp, "\n");
  2340. delete layer_default;
  2341. }
  2342. fclose(pp);
  2343. fclose(bp);
  2344. return 0;
  2345. }
  2346. int main(int argc, char** argv)
  2347. {
  2348. #if defined(__aarch64__) && defined(LINUX)
  2349. if (argc != 10)
  2350. {
  2351. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag] [dataname] [w] [h] [c]\n", argv[0]);
  2352. return -1;
  2353. }
  2354. const char* dataname = argv[6];
  2355. int inw = atoi(argv[7]);
  2356. int inh = atoi(argv[8]);
  2357. int inc = atoi(argv[9]);
  2358. #else
  2359. if (argc != 6)
  2360. {
  2361. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag]\n", argv[0]);
  2362. return -1;
  2363. }
  2364. #endif // defined(__aarch64__) && defined(LINUX)
  2365. const char* inparam = argv[1];
  2366. const char* inbin = argv[2];
  2367. const char* outparam = argv[3];
  2368. const char* outbin = argv[4];
  2369. int flag = atoi(argv[5]);
  2370. NetOptimize optimizer;
  2371. if (flag == 65536)
  2372. {
  2373. optimizer.storage_type = 1;
  2374. }
  2375. else
  2376. {
  2377. optimizer.storage_type = 0;
  2378. }
  2379. optimizer.load_param(inparam);
  2380. if (strcmp(inbin, "null") == 0)
  2381. {
  2382. DataReaderFromEmpty dr;
  2383. optimizer.load_model(dr);
  2384. }
  2385. else
  2386. optimizer.load_model(inbin);
  2387. #if defined(__aarch64__) && defined(LINUX)
  2388. optimizer.find_fastest_fp32_conv(dataname, inw, inh, inc);
  2389. #endif // defined(__aarch64__) && defined(LINUX)
  2390. optimizer.fuse_batchnorm_scale();
  2391. optimizer.fuse_convolution_batchnorm();
  2392. optimizer.fuse_convolutiondepthwise_batchnorm();
  2393. optimizer.fuse_deconvolution_batchnorm();
  2394. optimizer.fuse_deconvolutiondepthwise_batchnorm();
  2395. optimizer.fuse_innerproduct_batchnorm();
  2396. optimizer.fuse_innerproduct_dropout();
  2397. optimizer.fuse_convolution_activation();
  2398. optimizer.fuse_convolutiondepthwise_activation();
  2399. optimizer.fuse_deconvolution_activation();
  2400. optimizer.fuse_deconvolutiondepthwise_activation();
  2401. optimizer.fuse_innerproduct_activation();
  2402. optimizer.fuse_memorydata_binaryop();
  2403. optimizer.fuse_binaryop_eltwise();
  2404. optimizer.eliminate_dropout();
  2405. optimizer.eliminate_pooling1x1();
  2406. optimizer.eliminate_noop();
  2407. optimizer.eliminate_flatten_after_global_pooling();
  2408. optimizer.eliminate_reshape_after_global_pooling();
  2409. optimizer.eliminate_reshape_before_binaryop();
  2410. optimizer.replace_convolution_with_innerproduct_after_global_pooling();
  2411. optimizer.replace_convolution_with_innerproduct_after_innerproduct();
  2412. optimizer.eliminate_flatten_after_innerproduct();
  2413. optimizer.eliminate_orphaned_memorydata();
  2414. optimizer.shape_inference();
  2415. optimizer.save(outparam, outbin);
  2416. return 0;
  2417. }