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