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 79 kB

6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #ifdef _MSC_VER
  15. #define _CRT_SECURE_NO_DEPRECATE
  16. #endif
  17. #include <algorithm>
  18. #include <map>
  19. #include <set>
  20. #include <vector>
  21. // ncnn public header
  22. #include "datareader.h"
  23. #include "layer.h"
  24. #include "layer_type.h"
  25. #include "net.h"
  26. // ncnn private header
  27. #include "modelwriter.h"
  28. class DataReaderFromEmpty : public ncnn::DataReader
  29. {
  30. public:
  31. virtual int scan(const char* format, void* p) const
  32. {
  33. return 0;
  34. }
  35. virtual size_t read(void* /*buf*/, size_t size) const
  36. {
  37. return size;
  38. }
  39. };
  40. class NetOptimize : public ModelWriter
  41. {
  42. public:
  43. NetOptimize();
  44. public:
  45. int fuse_batchnorm_scale();
  46. int fuse_convolution_batchnorm();
  47. int fuse_convolution_mul();
  48. int fuse_convolution_add();
  49. int fuse_convolutiondepthwise_batchnorm();
  50. int fuse_convolutiondepthwise_mul();
  51. int fuse_convolutiondepthwise_add();
  52. int fuse_deconvolution_batchnorm();
  53. int fuse_deconvolution_mul();
  54. int fuse_deconvolution_add();
  55. int fuse_deconvolutiondepthwise_batchnorm();
  56. int fuse_innerproduct_batchnorm();
  57. int fuse_innerproduct_add();
  58. int fuse_innerproduct_dropout();
  59. int fuse_convolution_activation();
  60. int fuse_convolutiondepthwise_activation();
  61. int fuse_deconvolution_activation();
  62. int fuse_deconvolutiondepthwise_activation();
  63. int fuse_innerproduct_activation();
  64. int fuse_memorydata_binaryop();
  65. int fuse_binaryop_eltwise();
  66. int eliminate_dropout();
  67. int eliminate_pooling1x1();
  68. int eliminate_noop();
  69. int eliminate_orphaned_memorydata();
  70. int eliminate_flatten_after_global_pooling();
  71. int eliminate_reshape_after_global_pooling();
  72. int eliminate_flatten_after_innerproduct();
  73. int eliminate_reshape_before_binaryop();
  74. int replace_reduction_with_global_pooling();
  75. int replace_prelu_with_leaky_relu();
  76. int replace_convolution_with_innerproduct_after_global_pooling();
  77. int replace_convolution_with_innerproduct_after_innerproduct();
  78. };
  79. NetOptimize::NetOptimize()
  80. : ModelWriter()
  81. {
  82. }
  83. int NetOptimize::fuse_batchnorm_scale()
  84. {
  85. const size_t layer_count = layers.size();
  86. for (size_t i = 0; i < layer_count; i++)
  87. {
  88. if (layers[i]->type != "BatchNorm")
  89. continue;
  90. // BatchNorm - Scale
  91. int top_blob_index = layers[i]->tops[0];
  92. size_t j = i + 1;
  93. for (; j < layer_count; j++)
  94. {
  95. if (layers[j]->type != "Scale")
  96. continue;
  97. if (layers[j]->bottoms.size() != 1)
  98. continue;
  99. if (layers[j]->bottoms[0] == top_blob_index)
  100. break;
  101. }
  102. if (j == layer_count)
  103. continue;
  104. // fuse BatchNorm - Scale to BatchNorm
  105. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[i];
  106. ncnn::Scale* scale = (ncnn::Scale*)layers[j];
  107. fprintf(stderr, "fuse_batchnorm_scale %s %s\n", batchnorm->name.c_str(), scale->name.c_str());
  108. {
  109. // v = ((v - mean) / sqrt(var + eps) * slope + bias) * s + b
  110. // = (v - mean) / sqrt(var + eps) * (slope * s) + (bias * s + b)
  111. int channels = batchnorm->channels;
  112. float* slope = batchnorm->slope_data;
  113. float* bias = batchnorm->bias_data;
  114. for (int q = 0; q < channels; q++)
  115. {
  116. slope[q] = slope[q] * scale->scale_data[q];
  117. if (scale->bias_term)
  118. bias[q] = bias[q] * scale->scale_data[q] + scale->bias_data[q];
  119. else
  120. bias[q] = bias[q] * scale->scale_data[q];
  121. }
  122. }
  123. int top_blob_index_final = scale->tops[0];
  124. batchnorm->tops[0] = top_blob_index_final;
  125. blobs[top_blob_index_final].producer = i;
  126. scale->type = "ncnnfused";
  127. }
  128. return 0;
  129. }
  130. int NetOptimize::fuse_convolution_batchnorm()
  131. {
  132. const size_t layer_count = layers.size();
  133. for (size_t i = 0; i < layer_count; i++)
  134. {
  135. if (layers[i]->type != "Convolution")
  136. continue;
  137. // Convolution - BatchNorm
  138. int top_blob_index = layers[i]->tops[0];
  139. size_t j = i + 1;
  140. for (; j < layer_count; j++)
  141. {
  142. if (layers[j]->type != "BatchNorm")
  143. continue;
  144. if (layers[j]->bottoms.size() != 1)
  145. continue;
  146. if (layers[j]->bottoms[0] == top_blob_index)
  147. break;
  148. }
  149. if (j == layer_count)
  150. continue;
  151. // fuse Convolution - BatchNorm to Convolution
  152. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  153. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  154. fprintf(stderr, "fuse_convolution_batchnorm %s %s\n", convolution->name.c_str(), batchnorm->name.c_str());
  155. {
  156. int channels = batchnorm->channels;
  157. float eps = batchnorm->eps;
  158. // a = bias - slope * mean / sqrt(var + eps)
  159. // b = slope / sqrt(var + eps)
  160. // value = value * b + a
  161. std::vector<float> a(channels);
  162. std::vector<float> b(channels);
  163. for (int i = 0; i < channels; i++)
  164. {
  165. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  166. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  167. b[i] = batchnorm->slope_data[i] / sqrt_var;
  168. }
  169. if (convolution->bias_term == 0)
  170. {
  171. // init bias as zero
  172. convolution->bias_term = 1;
  173. convolution->bias_data = ncnn::Mat(channels);
  174. convolution->bias_data.fill(0.f);
  175. }
  176. const int weight_per_outch = convolution->weight_data_size / channels;
  177. float* weight = convolution->weight_data;
  178. float* bias = convolution->bias_data;
  179. for (int i = 0; i < channels; i++)
  180. {
  181. float* conv_weight_outch = weight + weight_per_outch * i;
  182. for (int j = 0; j < weight_per_outch; j++)
  183. {
  184. conv_weight_outch[j] *= b[i];
  185. }
  186. bias[i] = bias[i] * b[i] + a[i];
  187. }
  188. }
  189. int top_blob_index_final = batchnorm->tops[0];
  190. convolution->tops[0] = top_blob_index_final;
  191. blobs[top_blob_index_final].producer = i;
  192. batchnorm->type = "ncnnfused";
  193. }
  194. return 0;
  195. }
  196. int NetOptimize::fuse_convolution_mul()
  197. {
  198. const size_t layer_count = layers.size();
  199. for (size_t i = 0; i < layer_count; i++)
  200. {
  201. if (layers[i]->type != "Convolution")
  202. continue;
  203. // Convolution - BinaryOp
  204. int top_blob_index = layers[i]->tops[0];
  205. size_t j = i + 1;
  206. for (; j < layer_count; j++)
  207. {
  208. if (layers[j]->type != "BinaryOp")
  209. continue;
  210. if (layers[j]->bottoms.size() != 2)
  211. continue;
  212. if (layers[j]->bottoms[0] == top_blob_index)
  213. break;
  214. }
  215. if (j == layer_count)
  216. continue;
  217. // fuse Convolution - BinaryOp to Convolution
  218. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  219. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  220. if (binaryop->op_type != 2 || binaryop->with_scalar)
  221. continue;
  222. // MemoryData - ..... - BinaryOp
  223. size_t k = 0;
  224. for (; k < j; k++)
  225. {
  226. if (layers[k]->type != "MemoryData")
  227. continue;
  228. if (layers[k]->tops[0] == binaryop->bottoms[1])
  229. break;
  230. }
  231. if (k == j)
  232. continue;
  233. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  234. int channels = convolution->num_output;
  235. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  236. {
  237. // not bias-like broadcasting type
  238. continue;
  239. }
  240. fprintf(stderr, "fuse_convolution_mul %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
  241. {
  242. const int weight_per_outch = convolution->weight_data_size / channels;
  243. float* weight = convolution->weight_data;
  244. float* bias = convolution->bias_data;
  245. for (int i = 0; i < channels; i++)
  246. {
  247. float* conv_weight_outch = weight + weight_per_outch * i;
  248. for (int j = 0; j < weight_per_outch; j++)
  249. {
  250. conv_weight_outch[j] *= memorydata->data[i];
  251. }
  252. if (bias)
  253. {
  254. bias[i] = bias[i] * memorydata->data[i];
  255. }
  256. }
  257. }
  258. int top_blob_index_final = binaryop->tops[0];
  259. convolution->tops[0] = top_blob_index_final;
  260. blobs[top_blob_index_final].producer = i;
  261. binaryop->type = "ncnnfused";
  262. }
  263. return 0;
  264. }
  265. int NetOptimize::fuse_convolution_add()
  266. {
  267. const size_t layer_count = layers.size();
  268. for (size_t i = 0; i < layer_count; i++)
  269. {
  270. if (layers[i]->type != "Convolution")
  271. continue;
  272. // Convolution - BinaryOp
  273. int top_blob_index = layers[i]->tops[0];
  274. size_t j = i + 1;
  275. for (; j < layer_count; j++)
  276. {
  277. if (layers[j]->type != "BinaryOp")
  278. continue;
  279. if (layers[j]->bottoms.size() != 2)
  280. continue;
  281. if (layers[j]->bottoms[0] == top_blob_index)
  282. break;
  283. }
  284. if (j == layer_count)
  285. continue;
  286. // fuse Convolution - BinaryOp to Convolution
  287. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  288. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  289. if (binaryop->op_type != 0 || binaryop->with_scalar)
  290. continue;
  291. // MemoryData - ..... - BinaryOp
  292. size_t k = 0;
  293. for (; k < j; k++)
  294. {
  295. if (layers[k]->type != "MemoryData")
  296. continue;
  297. if (layers[k]->tops[0] == binaryop->bottoms[1])
  298. break;
  299. }
  300. if (k == j)
  301. continue;
  302. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  303. int channels = convolution->num_output;
  304. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  305. {
  306. // not bias-like broadcasting type
  307. continue;
  308. }
  309. fprintf(stderr, "fuse_convolution_add %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
  310. {
  311. if (convolution->bias_term == 0)
  312. {
  313. // init bias
  314. convolution->bias_term = 1;
  315. convolution->bias_data = memorydata->data;
  316. }
  317. else
  318. {
  319. float* bias = convolution->bias_data;
  320. for (int i = 0; i < channels; i++)
  321. {
  322. bias[i] = bias[i] + memorydata->data[i];
  323. }
  324. }
  325. }
  326. int top_blob_index_final = binaryop->tops[0];
  327. convolution->tops[0] = top_blob_index_final;
  328. blobs[top_blob_index_final].producer = i;
  329. binaryop->type = "ncnnfused";
  330. }
  331. return 0;
  332. }
  333. int NetOptimize::fuse_convolutiondepthwise_batchnorm()
  334. {
  335. const size_t layer_count = layers.size();
  336. for (size_t i = 0; i < layer_count; i++)
  337. {
  338. if (layers[i]->type != "ConvolutionDepthWise")
  339. continue;
  340. // ConvolutionDepthWise - BatchNorm
  341. int top_blob_index = layers[i]->tops[0];
  342. size_t j = i + 1;
  343. for (; j < layer_count; j++)
  344. {
  345. if (layers[j]->type != "BatchNorm")
  346. continue;
  347. if (layers[j]->bottoms.size() != 1)
  348. continue;
  349. if (layers[j]->bottoms[0] == top_blob_index)
  350. break;
  351. }
  352. if (j == layer_count)
  353. continue;
  354. // fuse ConvolutionDepthWise - BatchNorm to ConvolutionDepthWise
  355. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  356. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  357. fprintf(stderr, "fuse_convolutiondepthwise_batchnorm %s %s\n", convolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  358. {
  359. int channels = batchnorm->channels;
  360. float eps = batchnorm->eps;
  361. // a = bias - slope * mean / sqrt(var + eps)
  362. // b = slope / sqrt(var + eps)
  363. // value = value * b + a
  364. std::vector<float> a(channels);
  365. std::vector<float> b(channels);
  366. for (int i = 0; i < channels; i++)
  367. {
  368. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  369. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  370. b[i] = batchnorm->slope_data[i] / sqrt_var;
  371. }
  372. if (convolutiondepthwise->bias_term == 0)
  373. {
  374. // init bias as zero
  375. convolutiondepthwise->bias_term = 1;
  376. convolutiondepthwise->bias_data = ncnn::Mat(channels);
  377. convolutiondepthwise->bias_data.fill(0.f);
  378. }
  379. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  380. float* weight = convolutiondepthwise->weight_data;
  381. float* bias = convolutiondepthwise->bias_data;
  382. for (int i = 0; i < channels; i++)
  383. {
  384. float* conv_weight_outch = weight + weight_per_outch * i;
  385. for (int j = 0; j < weight_per_outch; j++)
  386. {
  387. conv_weight_outch[j] *= b[i];
  388. }
  389. bias[i] = bias[i] * b[i] + a[i];
  390. }
  391. }
  392. int top_blob_index_final = batchnorm->tops[0];
  393. convolutiondepthwise->tops[0] = top_blob_index_final;
  394. blobs[top_blob_index_final].producer = i;
  395. batchnorm->type = "ncnnfused";
  396. }
  397. return 0;
  398. }
  399. int NetOptimize::fuse_convolutiondepthwise_mul()
  400. {
  401. const size_t layer_count = layers.size();
  402. for (size_t i = 0; i < layer_count; i++)
  403. {
  404. if (layers[i]->type != "ConvolutionDepthWise")
  405. continue;
  406. // ConvolutionDepthWise - BinaryOp
  407. int top_blob_index = layers[i]->tops[0];
  408. size_t j = i + 1;
  409. for (; j < layer_count; j++)
  410. {
  411. if (layers[j]->type != "BinaryOp")
  412. continue;
  413. if (layers[j]->bottoms.size() != 2)
  414. continue;
  415. if (layers[j]->bottoms[0] == top_blob_index)
  416. break;
  417. }
  418. if (j == layer_count)
  419. continue;
  420. // fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
  421. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  422. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  423. if (binaryop->op_type != 2 || binaryop->with_scalar)
  424. continue;
  425. // MemoryData - ..... - BinaryOp
  426. size_t k = 0;
  427. for (; k < j; k++)
  428. {
  429. if (layers[k]->type != "MemoryData")
  430. continue;
  431. if (layers[k]->tops[0] == binaryop->bottoms[1])
  432. break;
  433. }
  434. if (k == j)
  435. continue;
  436. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  437. int channels = convolutiondepthwise->num_output;
  438. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  439. {
  440. // not bias-like broadcasting type
  441. continue;
  442. }
  443. fprintf(stderr, "fuse_convolutiondepthwise_mul %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
  444. {
  445. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  446. float* weight = convolutiondepthwise->weight_data;
  447. float* bias = convolutiondepthwise->bias_data;
  448. for (int i = 0; i < channels; i++)
  449. {
  450. float* conv_weight_outch = weight + weight_per_outch * i;
  451. for (int j = 0; j < weight_per_outch; j++)
  452. {
  453. conv_weight_outch[j] *= memorydata->data[i];
  454. }
  455. if (bias)
  456. {
  457. bias[i] = bias[i] * memorydata->data[i];
  458. }
  459. }
  460. }
  461. int top_blob_index_final = binaryop->tops[0];
  462. convolutiondepthwise->tops[0] = top_blob_index_final;
  463. blobs[top_blob_index_final].producer = i;
  464. binaryop->type = "ncnnfused";
  465. }
  466. return 0;
  467. }
  468. int NetOptimize::fuse_convolutiondepthwise_add()
  469. {
  470. const size_t layer_count = layers.size();
  471. for (size_t i = 0; i < layer_count; i++)
  472. {
  473. if (layers[i]->type != "ConvolutionDepthWise")
  474. continue;
  475. // ConvolutionDepthWise - BinaryOp
  476. int top_blob_index = layers[i]->tops[0];
  477. size_t j = i + 1;
  478. for (; j < layer_count; j++)
  479. {
  480. if (layers[j]->type != "BinaryOp")
  481. continue;
  482. if (layers[j]->bottoms.size() != 2)
  483. continue;
  484. if (layers[j]->bottoms[0] == top_blob_index)
  485. break;
  486. }
  487. if (j == layer_count)
  488. continue;
  489. // fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
  490. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  491. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  492. if (binaryop->op_type != 0 || binaryop->with_scalar)
  493. continue;
  494. // MemoryData - ..... - BinaryOp
  495. size_t k = 0;
  496. for (; k < j; k++)
  497. {
  498. if (layers[k]->type != "MemoryData")
  499. continue;
  500. if (layers[k]->tops[0] == binaryop->bottoms[1])
  501. break;
  502. }
  503. if (k == j)
  504. continue;
  505. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  506. int channels = convolutiondepthwise->num_output;
  507. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  508. {
  509. // not bias-like broadcasting type
  510. continue;
  511. }
  512. fprintf(stderr, "fuse_convolutiondepthwise_add %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
  513. {
  514. if (convolutiondepthwise->bias_term == 0)
  515. {
  516. // init bias
  517. convolutiondepthwise->bias_term = 1;
  518. convolutiondepthwise->bias_data = memorydata->data;
  519. }
  520. else
  521. {
  522. float* bias = convolutiondepthwise->bias_data;
  523. for (int i = 0; i < channels; i++)
  524. {
  525. bias[i] = bias[i] + memorydata->data[i];
  526. }
  527. }
  528. }
  529. int top_blob_index_final = binaryop->tops[0];
  530. convolutiondepthwise->tops[0] = top_blob_index_final;
  531. blobs[top_blob_index_final].producer = i;
  532. binaryop->type = "ncnnfused";
  533. }
  534. return 0;
  535. }
  536. int NetOptimize::fuse_deconvolution_batchnorm()
  537. {
  538. const size_t layer_count = layers.size();
  539. for (size_t i = 0; i < layer_count; i++)
  540. {
  541. if (layers[i]->type != "Deconvolution")
  542. continue;
  543. // Deconvolution - BatchNorm
  544. int top_blob_index = layers[i]->tops[0];
  545. size_t j = i + 1;
  546. for (; j < layer_count; j++)
  547. {
  548. if (layers[j]->type != "BatchNorm")
  549. continue;
  550. if (layers[j]->bottoms.size() != 1)
  551. continue;
  552. if (layers[j]->bottoms[0] == top_blob_index)
  553. break;
  554. }
  555. if (j == layer_count)
  556. continue;
  557. // fuse Deconvolution - BatchNorm to Deconvolution
  558. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  559. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  560. fprintf(stderr, "fuse_deconvolution_batchnorm %s %s\n", deconvolution->name.c_str(), batchnorm->name.c_str());
  561. {
  562. int channels = batchnorm->channels;
  563. float eps = batchnorm->eps;
  564. // a = bias - slope * mean / sqrt(var + eps)
  565. // b = slope / sqrt(var + eps)
  566. // value = value * b + a
  567. std::vector<float> a(channels);
  568. std::vector<float> b(channels);
  569. for (int i = 0; i < channels; i++)
  570. {
  571. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  572. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  573. b[i] = batchnorm->slope_data[i] / sqrt_var;
  574. }
  575. if (deconvolution->bias_term == 0)
  576. {
  577. // init bias as zero
  578. deconvolution->bias_term = 1;
  579. deconvolution->bias_data = ncnn::Mat(channels);
  580. deconvolution->bias_data.fill(0.f);
  581. }
  582. const int weight_per_outch = deconvolution->weight_data_size / channels;
  583. float* weight = deconvolution->weight_data;
  584. float* bias = deconvolution->bias_data;
  585. for (int i = 0; i < channels; i++)
  586. {
  587. float* conv_weight_outch = weight + weight_per_outch * i;
  588. for (int j = 0; j < weight_per_outch; j++)
  589. {
  590. conv_weight_outch[j] *= b[i];
  591. }
  592. bias[i] = bias[i] * b[i] + a[i];
  593. }
  594. }
  595. int top_blob_index_final = batchnorm->tops[0];
  596. deconvolution->tops[0] = top_blob_index_final;
  597. blobs[top_blob_index_final].producer = i;
  598. batchnorm->type = "ncnnfused";
  599. }
  600. return 0;
  601. }
  602. int NetOptimize::fuse_deconvolution_mul()
  603. {
  604. const size_t layer_count = layers.size();
  605. for (size_t i = 0; i < layer_count; i++)
  606. {
  607. if (layers[i]->type != "Deconvolution")
  608. continue;
  609. // Deconvolution - BinaryOp
  610. int top_blob_index = layers[i]->tops[0];
  611. size_t j = i + 1;
  612. for (; j < layer_count; j++)
  613. {
  614. if (layers[j]->type != "BinaryOp")
  615. continue;
  616. if (layers[j]->bottoms.size() != 2)
  617. continue;
  618. if (layers[j]->bottoms[0] == top_blob_index)
  619. break;
  620. }
  621. if (j == layer_count)
  622. continue;
  623. // fuse Deconvolution - BinaryOp to Deconvolution
  624. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  625. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  626. if (binaryop->op_type != 2 || binaryop->with_scalar)
  627. continue;
  628. // MemoryData - ..... - BinaryOp
  629. size_t k = 0;
  630. for (; k < j; k++)
  631. {
  632. if (layers[k]->type != "MemoryData")
  633. continue;
  634. if (layers[k]->tops[0] == binaryop->bottoms[1])
  635. break;
  636. }
  637. if (k == j)
  638. continue;
  639. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  640. int channels = deconvolution->num_output;
  641. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  642. {
  643. // not bias-like broadcasting type
  644. continue;
  645. }
  646. fprintf(stderr, "fuse_deconvolution_mul %s %s\n", deconvolution->name.c_str(), binaryop->name.c_str());
  647. {
  648. const int weight_per_outch = deconvolution->weight_data_size / channels;
  649. float* weight = deconvolution->weight_data;
  650. float* bias = deconvolution->bias_data;
  651. for (int i = 0; i < channels; i++)
  652. {
  653. float* conv_weight_outch = weight + weight_per_outch * i;
  654. for (int j = 0; j < weight_per_outch; j++)
  655. {
  656. conv_weight_outch[j] *= memorydata->data[i];
  657. }
  658. if (bias)
  659. {
  660. bias[i] = bias[i] * memorydata->data[i];
  661. }
  662. }
  663. }
  664. int top_blob_index_final = binaryop->tops[0];
  665. deconvolution->tops[0] = top_blob_index_final;
  666. blobs[top_blob_index_final].producer = i;
  667. binaryop->type = "ncnnfused";
  668. }
  669. return 0;
  670. }
  671. int NetOptimize::fuse_deconvolution_add()
  672. {
  673. const size_t layer_count = layers.size();
  674. for (size_t i = 0; i < layer_count; i++)
  675. {
  676. if (layers[i]->type != "Deconvolution")
  677. continue;
  678. // Deconvolution - BinaryOp
  679. int top_blob_index = layers[i]->tops[0];
  680. size_t j = i + 1;
  681. for (; j < layer_count; j++)
  682. {
  683. if (layers[j]->type != "BinaryOp")
  684. continue;
  685. if (layers[j]->bottoms.size() != 2)
  686. continue;
  687. if (layers[j]->bottoms[0] == top_blob_index)
  688. break;
  689. }
  690. if (j == layer_count)
  691. continue;
  692. // fuse Deconvolution - BinaryOp to Deconvolution
  693. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  694. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  695. if (binaryop->op_type != 0 || binaryop->with_scalar)
  696. continue;
  697. // MemoryData - ..... - BinaryOp
  698. size_t k = 0;
  699. for (; k < j; k++)
  700. {
  701. if (layers[k]->type != "MemoryData")
  702. continue;
  703. if (layers[k]->tops[0] == binaryop->bottoms[1])
  704. break;
  705. }
  706. if (k == j)
  707. continue;
  708. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  709. int channels = deconvolution->num_output;
  710. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  711. {
  712. // not bias-like broadcasting type
  713. continue;
  714. }
  715. fprintf(stderr, "fuse_deconvolution_add %s %s\n", deconvolution->name.c_str(), binaryop->name.c_str());
  716. {
  717. if (deconvolution->bias_term == 0)
  718. {
  719. // init bias
  720. deconvolution->bias_term = 1;
  721. deconvolution->bias_data = memorydata->data;
  722. }
  723. else
  724. {
  725. float* bias = deconvolution->bias_data;
  726. for (int i = 0; i < channels; i++)
  727. {
  728. bias[i] = bias[i] + memorydata->data[i];
  729. }
  730. }
  731. }
  732. int top_blob_index_final = binaryop->tops[0];
  733. deconvolution->tops[0] = top_blob_index_final;
  734. blobs[top_blob_index_final].producer = i;
  735. binaryop->type = "ncnnfused";
  736. }
  737. return 0;
  738. }
  739. int NetOptimize::fuse_deconvolutiondepthwise_batchnorm()
  740. {
  741. const size_t layer_count = layers.size();
  742. for (size_t i = 0; i < layer_count; i++)
  743. {
  744. if (layers[i]->type != "DeconvolutionDepthWise")
  745. continue;
  746. // DeconvolutionDepthWise - BatchNorm
  747. int top_blob_index = layers[i]->tops[0];
  748. size_t j = i + 1;
  749. for (; j < layer_count; j++)
  750. {
  751. if (layers[j]->type != "BatchNorm")
  752. continue;
  753. if (layers[j]->bottoms.size() != 1)
  754. continue;
  755. if (layers[j]->bottoms[0] == top_blob_index)
  756. break;
  757. }
  758. if (j == layer_count)
  759. continue;
  760. // fuse DeconvolutionDepthWise - BatchNorm to DeconvolutionDepthWise
  761. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  762. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  763. fprintf(stderr, "fuse_deconvolutiondepthwise_batchnorm %s %s\n", deconvolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  764. {
  765. int channels = batchnorm->channels;
  766. float eps = batchnorm->eps;
  767. // a = bias - slope * mean / sqrt(var + eps)
  768. // b = slope / sqrt(var + eps)
  769. // value = value * b + a
  770. std::vector<float> a(channels);
  771. std::vector<float> b(channels);
  772. for (int i = 0; i < channels; i++)
  773. {
  774. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  775. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  776. b[i] = batchnorm->slope_data[i] / sqrt_var;
  777. }
  778. if (deconvolutiondepthwise->bias_term == 0)
  779. {
  780. // init bias as zero
  781. deconvolutiondepthwise->bias_term = 1;
  782. deconvolutiondepthwise->bias_data = ncnn::Mat(channels);
  783. deconvolutiondepthwise->bias_data.fill(0.f);
  784. }
  785. const int weight_per_outch = deconvolutiondepthwise->weight_data_size / channels;
  786. float* weight = deconvolutiondepthwise->weight_data;
  787. float* bias = deconvolutiondepthwise->bias_data;
  788. for (int i = 0; i < channels; i++)
  789. {
  790. float* conv_weight_outch = weight + weight_per_outch * i;
  791. for (int j = 0; j < weight_per_outch; j++)
  792. {
  793. conv_weight_outch[j] *= b[i];
  794. }
  795. bias[i] = bias[i] * b[i] + a[i];
  796. }
  797. }
  798. int top_blob_index_final = batchnorm->tops[0];
  799. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  800. blobs[top_blob_index_final].producer = i;
  801. batchnorm->type = "ncnnfused";
  802. }
  803. return 0;
  804. }
  805. int NetOptimize::fuse_innerproduct_batchnorm()
  806. {
  807. const size_t layer_count = layers.size();
  808. for (size_t i = 0; i < layer_count; i++)
  809. {
  810. if (layers[i]->type != "InnerProduct")
  811. continue;
  812. // InnerProduct - BatchNorm
  813. int top_blob_index = layers[i]->tops[0];
  814. size_t j = i + 1;
  815. for (; j < layer_count; j++)
  816. {
  817. if (layers[j]->type != "BatchNorm")
  818. continue;
  819. if (layers[j]->bottoms.size() != 1)
  820. continue;
  821. if (layers[j]->bottoms[0] == top_blob_index)
  822. break;
  823. }
  824. if (j == layer_count)
  825. continue;
  826. // fuse InnerProduct - BatchNorm to InnerProduct
  827. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  828. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  829. fprintf(stderr, "fuse_innerproduct_batchnorm %s %s\n", innerproduct->name.c_str(), batchnorm->name.c_str());
  830. {
  831. int channels = batchnorm->channels;
  832. float eps = batchnorm->eps;
  833. // a = bias - slope * mean / sqrt(var + eps)
  834. // b = slope / sqrt(var + eps)
  835. // value = value * b + a
  836. std::vector<float> a(channels);
  837. std::vector<float> b(channels);
  838. for (int i = 0; i < channels; i++)
  839. {
  840. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  841. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  842. b[i] = batchnorm->slope_data[i] / sqrt_var;
  843. }
  844. if (innerproduct->bias_term == 0)
  845. {
  846. // init bias as zero
  847. innerproduct->bias_term = 1;
  848. innerproduct->bias_data = ncnn::Mat(channels);
  849. innerproduct->bias_data.fill(0.f);
  850. }
  851. const int weight_per_outch = innerproduct->weight_data_size / channels;
  852. float* weight = innerproduct->weight_data;
  853. float* bias = innerproduct->bias_data;
  854. for (int i = 0; i < channels; i++)
  855. {
  856. float* conv_weight_outch = weight + weight_per_outch * i;
  857. for (int j = 0; j < weight_per_outch; j++)
  858. {
  859. conv_weight_outch[j] *= b[i];
  860. }
  861. bias[i] = bias[i] * b[i] + a[i];
  862. }
  863. }
  864. int top_blob_index_final = batchnorm->tops[0];
  865. innerproduct->tops[0] = top_blob_index_final;
  866. blobs[top_blob_index_final].producer = i;
  867. batchnorm->type = "ncnnfused";
  868. }
  869. return 0;
  870. }
  871. int NetOptimize::fuse_innerproduct_add()
  872. {
  873. const size_t layer_count = layers.size();
  874. for (size_t i = 0; i < layer_count; i++)
  875. {
  876. if (layers[i]->type != "InnerProduct")
  877. continue;
  878. // InnerProduct - BinaryOp
  879. int top_blob_index = layers[i]->tops[0];
  880. size_t j = i + 1;
  881. for (; j < layer_count; j++)
  882. {
  883. if (layers[j]->type != "BinaryOp")
  884. continue;
  885. if (layers[j]->bottoms.size() != 2)
  886. continue;
  887. if (layers[j]->bottoms[0] == top_blob_index)
  888. break;
  889. }
  890. if (j == layer_count)
  891. continue;
  892. // fuse InnerProduct - BinaryOp to InnerProduct
  893. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  894. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  895. if (binaryop->op_type != 0 || binaryop->with_scalar)
  896. continue;
  897. // MemoryData - ..... - BinaryOp
  898. size_t k = 0;
  899. for (; k < j; k++)
  900. {
  901. if (layers[k]->type != "MemoryData")
  902. continue;
  903. if (layers[k]->tops[0] == binaryop->bottoms[1])
  904. break;
  905. }
  906. if (k == j)
  907. continue;
  908. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  909. int channels = innerproduct->num_output;
  910. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  911. {
  912. // not bias-like broadcasting type
  913. continue;
  914. }
  915. fprintf(stderr, "fuse_innerproduct_add %s %s\n", innerproduct->name.c_str(), binaryop->name.c_str());
  916. {
  917. if (innerproduct->bias_term == 0)
  918. {
  919. // init bias
  920. innerproduct->bias_term = 1;
  921. innerproduct->bias_data = memorydata->data;
  922. }
  923. else
  924. {
  925. float* bias = innerproduct->bias_data;
  926. for (int i = 0; i < channels; i++)
  927. {
  928. bias[i] = bias[i] + memorydata->data[i];
  929. }
  930. }
  931. }
  932. int top_blob_index_final = binaryop->tops[0];
  933. innerproduct->tops[0] = top_blob_index_final;
  934. blobs[top_blob_index_final].producer = i;
  935. binaryop->type = "ncnnfused";
  936. }
  937. return 0;
  938. }
  939. int NetOptimize::fuse_innerproduct_dropout()
  940. {
  941. const size_t layer_count = layers.size();
  942. for (size_t i = 0; i < layer_count; i++)
  943. {
  944. if (layers[i]->type != "InnerProduct")
  945. continue;
  946. // InnerProduct - Dropout
  947. int top_blob_index = layers[i]->tops[0];
  948. size_t j = i + 1;
  949. for (; j < layer_count; j++)
  950. {
  951. if (layers[j]->type != "Dropout")
  952. continue;
  953. if (layers[j]->bottoms.size() != 1)
  954. continue;
  955. if (layers[j]->bottoms[0] == top_blob_index)
  956. break;
  957. }
  958. if (j == layer_count)
  959. continue;
  960. // fuse InnerProduct - Dropout to InnerProduct
  961. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  962. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[j];
  963. fprintf(stderr, "fuse_innerproduct_dropout %s %s\n", innerproduct->name.c_str(), dropout->name.c_str());
  964. float scale = dropout->scale;
  965. if (scale != 1.f)
  966. {
  967. const int num_output = innerproduct->num_output;
  968. const int weight_per_outch = innerproduct->weight_data_size / num_output;
  969. float* weight = innerproduct->weight_data;
  970. for (int i = 0; i < num_output; i++)
  971. {
  972. float* conv_weight_outch = weight + weight_per_outch * i;
  973. for (int j = 0; j < weight_per_outch; j++)
  974. {
  975. conv_weight_outch[j] *= scale;
  976. }
  977. }
  978. if (innerproduct->bias_term)
  979. {
  980. float* bias = innerproduct->bias_data;
  981. for (int i = 0; i < num_output; i++)
  982. {
  983. bias[i] *= scale;
  984. }
  985. }
  986. }
  987. int top_blob_index_final = dropout->tops[0];
  988. innerproduct->tops[0] = top_blob_index_final;
  989. blobs[top_blob_index_final].producer = i;
  990. dropout->type = "ncnnfused";
  991. }
  992. return 0;
  993. }
  994. int NetOptimize::fuse_convolution_activation()
  995. {
  996. const size_t layer_count = layers.size();
  997. for (size_t i = 0; i < layer_count; i++)
  998. {
  999. if (layers[i]->type != "Convolution")
  1000. continue;
  1001. // Convolution - Activation
  1002. int top_blob_index = layers[i]->tops[0];
  1003. size_t j = i + 1;
  1004. for (; j < layer_count; j++)
  1005. {
  1006. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid" && layers[j]->type != "Mish")
  1007. continue;
  1008. if (layers[j]->bottoms.size() != 1)
  1009. continue;
  1010. if (layers[j]->bottoms[0] == top_blob_index)
  1011. break;
  1012. }
  1013. if (j == layer_count)
  1014. continue;
  1015. // fuse Convolution - Activation to Convolution
  1016. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  1017. ncnn::Layer* activation = layers[j];
  1018. fprintf(stderr, "fuse_convolution_activation %s %s\n", convolution->name.c_str(), activation->name.c_str());
  1019. if (activation->type == "ReLU")
  1020. {
  1021. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1022. if (relu->slope == 0.f)
  1023. {
  1024. convolution->activation_type = 1;
  1025. }
  1026. else
  1027. {
  1028. convolution->activation_type = 2;
  1029. convolution->activation_params = ncnn::Mat(1);
  1030. convolution->activation_params[0] = relu->slope;
  1031. }
  1032. }
  1033. else if (activation->type == "Clip")
  1034. {
  1035. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1036. convolution->activation_type = 3;
  1037. convolution->activation_params = ncnn::Mat(2);
  1038. convolution->activation_params[0] = clip->min;
  1039. convolution->activation_params[1] = clip->max;
  1040. }
  1041. else if (activation->type == "Sigmoid")
  1042. {
  1043. convolution->activation_type = 4;
  1044. }
  1045. else if (activation->type == "Mish")
  1046. {
  1047. convolution->activation_type = 5;
  1048. }
  1049. int top_blob_index_final = activation->tops[0];
  1050. convolution->tops[0] = top_blob_index_final;
  1051. blobs[top_blob_index_final].producer = i;
  1052. activation->type = "ncnnfused";
  1053. }
  1054. return 0;
  1055. }
  1056. int NetOptimize::fuse_convolutiondepthwise_activation()
  1057. {
  1058. const size_t layer_count = layers.size();
  1059. for (size_t i = 0; i < layer_count; i++)
  1060. {
  1061. if (layers[i]->type != "ConvolutionDepthWise")
  1062. continue;
  1063. // ConvolutionDepthWise - Activation
  1064. int top_blob_index = layers[i]->tops[0];
  1065. size_t j = i + 1;
  1066. for (; j < layer_count; j++)
  1067. {
  1068. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid" && layers[j]->type != "Mish")
  1069. continue;
  1070. if (layers[j]->bottoms.size() != 1)
  1071. continue;
  1072. if (layers[j]->bottoms[0] == top_blob_index)
  1073. break;
  1074. }
  1075. if (j == layer_count)
  1076. continue;
  1077. // fuse ConvolutionDepthWise - Activation to ConvolutionDepthWise
  1078. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  1079. ncnn::Layer* activation = layers[j];
  1080. fprintf(stderr, "fuse_convolutiondepthwise_activation %s %s\n", convolutiondepthwise->name.c_str(), activation->name.c_str());
  1081. if (activation->type == "ReLU")
  1082. {
  1083. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1084. if (relu->slope == 0.f)
  1085. {
  1086. convolutiondepthwise->activation_type = 1;
  1087. }
  1088. else
  1089. {
  1090. convolutiondepthwise->activation_type = 2;
  1091. convolutiondepthwise->activation_params = ncnn::Mat(1);
  1092. convolutiondepthwise->activation_params[0] = relu->slope;
  1093. }
  1094. }
  1095. else if (activation->type == "Clip")
  1096. {
  1097. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1098. convolutiondepthwise->activation_type = 3;
  1099. convolutiondepthwise->activation_params = ncnn::Mat(2);
  1100. convolutiondepthwise->activation_params[0] = clip->min;
  1101. convolutiondepthwise->activation_params[1] = clip->max;
  1102. }
  1103. else if (activation->type == "Sigmoid")
  1104. {
  1105. convolutiondepthwise->activation_type = 4;
  1106. }
  1107. else if (activation->type == "Mish")
  1108. {
  1109. convolutiondepthwise->activation_type = 5;
  1110. }
  1111. int top_blob_index_final = activation->tops[0];
  1112. convolutiondepthwise->tops[0] = top_blob_index_final;
  1113. blobs[top_blob_index_final].producer = i;
  1114. activation->type = "ncnnfused";
  1115. }
  1116. return 0;
  1117. }
  1118. int NetOptimize::fuse_deconvolution_activation()
  1119. {
  1120. const size_t layer_count = layers.size();
  1121. for (size_t i = 0; i < layer_count; i++)
  1122. {
  1123. if (layers[i]->type != "Deconvolution")
  1124. continue;
  1125. // Deconvolution - Activation
  1126. int top_blob_index = layers[i]->tops[0];
  1127. size_t j = i + 1;
  1128. for (; j < layer_count; j++)
  1129. {
  1130. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1131. continue;
  1132. if (layers[j]->bottoms.size() != 1)
  1133. continue;
  1134. if (layers[j]->bottoms[0] == top_blob_index)
  1135. break;
  1136. }
  1137. if (j == layer_count)
  1138. continue;
  1139. // fuse Deconvolution - Activation to Deconvolution
  1140. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  1141. ncnn::Layer* activation = layers[j];
  1142. fprintf(stderr, "fuse_deconvolution_activation %s %s\n", deconvolution->name.c_str(), activation->name.c_str());
  1143. if (activation->type == "ReLU")
  1144. {
  1145. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1146. if (relu->slope == 0.f)
  1147. {
  1148. deconvolution->activation_type = 1;
  1149. }
  1150. else
  1151. {
  1152. deconvolution->activation_type = 2;
  1153. deconvolution->activation_params = ncnn::Mat(1);
  1154. deconvolution->activation_params[0] = relu->slope;
  1155. }
  1156. }
  1157. else if (activation->type == "Clip")
  1158. {
  1159. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1160. deconvolution->activation_type = 3;
  1161. deconvolution->activation_params = ncnn::Mat(2);
  1162. deconvolution->activation_params[0] = clip->min;
  1163. deconvolution->activation_params[1] = clip->max;
  1164. }
  1165. else if (activation->type == "Sigmoid")
  1166. {
  1167. deconvolution->activation_type = 4;
  1168. }
  1169. int top_blob_index_final = activation->tops[0];
  1170. deconvolution->tops[0] = top_blob_index_final;
  1171. blobs[top_blob_index_final].producer = i;
  1172. activation->type = "ncnnfused";
  1173. }
  1174. return 0;
  1175. }
  1176. int NetOptimize::fuse_deconvolutiondepthwise_activation()
  1177. {
  1178. const size_t layer_count = layers.size();
  1179. for (size_t i = 0; i < layer_count; i++)
  1180. {
  1181. if (layers[i]->type != "DeconvolutionDepthWise")
  1182. continue;
  1183. // DeconvolutionDepthWise - Activation
  1184. int top_blob_index = layers[i]->tops[0];
  1185. size_t j = i + 1;
  1186. for (; j < layer_count; j++)
  1187. {
  1188. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1189. continue;
  1190. if (layers[j]->bottoms.size() != 1)
  1191. continue;
  1192. if (layers[j]->bottoms[0] == top_blob_index)
  1193. break;
  1194. }
  1195. if (j == layer_count)
  1196. continue;
  1197. // fuse DeconvolutionDepthWise - Activation to DeconvolutionDepthWise
  1198. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  1199. ncnn::Layer* activation = layers[j];
  1200. fprintf(stderr, "fuse_deconvolutiondepthwise_activation %s %s\n", deconvolutiondepthwise->name.c_str(), activation->name.c_str());
  1201. if (activation->type == "ReLU")
  1202. {
  1203. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1204. if (relu->slope == 0.f)
  1205. {
  1206. deconvolutiondepthwise->activation_type = 1;
  1207. }
  1208. else
  1209. {
  1210. deconvolutiondepthwise->activation_type = 2;
  1211. deconvolutiondepthwise->activation_params = ncnn::Mat(1);
  1212. deconvolutiondepthwise->activation_params[0] = relu->slope;
  1213. }
  1214. }
  1215. else if (activation->type == "Clip")
  1216. {
  1217. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1218. deconvolutiondepthwise->activation_type = 3;
  1219. deconvolutiondepthwise->activation_params = ncnn::Mat(2);
  1220. deconvolutiondepthwise->activation_params[0] = clip->min;
  1221. deconvolutiondepthwise->activation_params[1] = clip->max;
  1222. }
  1223. else if (activation->type == "Sigmoid")
  1224. {
  1225. deconvolutiondepthwise->activation_type = 4;
  1226. }
  1227. int top_blob_index_final = activation->tops[0];
  1228. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  1229. blobs[top_blob_index_final].producer = i;
  1230. activation->type = "ncnnfused";
  1231. }
  1232. return 0;
  1233. }
  1234. int NetOptimize::fuse_innerproduct_activation()
  1235. {
  1236. const size_t layer_count = layers.size();
  1237. for (size_t i = 0; i < layer_count; i++)
  1238. {
  1239. if (layers[i]->type != "InnerProduct")
  1240. continue;
  1241. // InnerProduct - Activation
  1242. int top_blob_index = layers[i]->tops[0];
  1243. size_t j = i + 1;
  1244. for (; j < layer_count; j++)
  1245. {
  1246. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1247. continue;
  1248. if (layers[j]->bottoms.size() != 1)
  1249. continue;
  1250. if (layers[j]->bottoms[0] == top_blob_index)
  1251. break;
  1252. }
  1253. if (j == layer_count)
  1254. continue;
  1255. // fuse InnerProduct - Activation to InnerProduct
  1256. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1257. ncnn::Layer* activation = layers[j];
  1258. fprintf(stderr, "fuse_innerproduct_activation %s %s\n", innerproduct->name.c_str(), activation->name.c_str());
  1259. if (activation->type == "ReLU")
  1260. {
  1261. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1262. if (relu->slope == 0.f)
  1263. {
  1264. innerproduct->activation_type = 1;
  1265. }
  1266. else
  1267. {
  1268. innerproduct->activation_type = 2;
  1269. innerproduct->activation_params = ncnn::Mat(1);
  1270. innerproduct->activation_params[0] = relu->slope;
  1271. }
  1272. }
  1273. else if (activation->type == "Clip")
  1274. {
  1275. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1276. innerproduct->activation_type = 3;
  1277. innerproduct->activation_params = ncnn::Mat(2);
  1278. innerproduct->activation_params[0] = clip->min;
  1279. innerproduct->activation_params[1] = clip->max;
  1280. }
  1281. else if (activation->type == "Sigmoid")
  1282. {
  1283. innerproduct->activation_type = 4;
  1284. }
  1285. int top_blob_index_final = activation->tops[0];
  1286. innerproduct->tops[0] = top_blob_index_final;
  1287. blobs[top_blob_index_final].producer = i;
  1288. activation->type = "ncnnfused";
  1289. }
  1290. return 0;
  1291. }
  1292. int NetOptimize::fuse_memorydata_binaryop()
  1293. {
  1294. const size_t layer_count = layers.size();
  1295. for (size_t i = 0; i < layer_count; i++)
  1296. {
  1297. if (layers[i]->type != "MemoryData")
  1298. continue;
  1299. // MemoryData - BinaryOp
  1300. int top_blob_index = layers[i]->tops[0];
  1301. size_t j = i + 1;
  1302. for (; j < layer_count; j++)
  1303. {
  1304. if (layers[j]->type != "BinaryOp")
  1305. continue;
  1306. if (layers[j]->bottoms.size() != 2)
  1307. continue;
  1308. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1309. break;
  1310. }
  1311. if (j == layer_count)
  1312. continue;
  1313. // fuse MemoryData - BinaryOp to BinaryOp
  1314. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[i];
  1315. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1316. if (memorydata->w != 1 || memorydata->h != 0 || memorydata->c != 0)
  1317. {
  1318. // not a scalar
  1319. continue;
  1320. }
  1321. int memorydata_index = 1;
  1322. if (binaryop->bottoms[0] == top_blob_index)
  1323. {
  1324. int op_type = binaryop->op_type;
  1325. if (op_type == ncnn::BinaryOp::Operation_ADD
  1326. || op_type == ncnn::BinaryOp::Operation_MUL
  1327. || op_type == ncnn::BinaryOp::Operation_MAX
  1328. || op_type == ncnn::BinaryOp::Operation_MIN)
  1329. {
  1330. memorydata_index = 0;
  1331. }
  1332. else if (op_type == ncnn::BinaryOp::Operation_SUB)
  1333. {
  1334. binaryop->op_type = ncnn::BinaryOp::Operation_RSUB;
  1335. memorydata_index = 0;
  1336. }
  1337. else if (op_type == ncnn::BinaryOp::Operation_DIV)
  1338. {
  1339. binaryop->op_type = ncnn::BinaryOp::Operation_RDIV;
  1340. memorydata_index = 0;
  1341. }
  1342. else
  1343. {
  1344. // non interchangeable binaryop
  1345. continue;
  1346. }
  1347. }
  1348. float scalar = memorydata->data[0];
  1349. binaryop->with_scalar = 1;
  1350. binaryop->b = scalar;
  1351. fprintf(stderr, "fuse_memorydata_binaryop %s %s\n", memorydata->name.c_str(), binaryop->name.c_str());
  1352. binaryop->bottoms.erase(binaryop->bottoms.begin() + memorydata_index);
  1353. memorydata->type = "ncnnfused";
  1354. }
  1355. for (size_t i = 0; i < layer_count; i++)
  1356. {
  1357. if (layers[i]->type != "MemoryData")
  1358. continue;
  1359. // MemoryData - Split - BinaryOp
  1360. int top_blob_index = layers[i]->tops[0];
  1361. size_t j0 = i + 1;
  1362. for (; j0 < layer_count; j0++)
  1363. {
  1364. if (layers[j0]->type != "Split")
  1365. continue;
  1366. if (layers[j0]->bottoms.size() != 1)
  1367. continue;
  1368. if (layers[j0]->bottoms[0] == top_blob_index)
  1369. break;
  1370. }
  1371. if (j0 == layer_count)
  1372. continue;
  1373. int split_top_blob_index = -1;
  1374. size_t j1 = j0 + 1;
  1375. for (; j1 < layer_count; j1++)
  1376. {
  1377. if (layers[j1]->type != "BinaryOp")
  1378. continue;
  1379. if (layers[j1]->bottoms.size() != 2)
  1380. continue;
  1381. for (int k = 0; k < (int)layers[j0]->tops.size(); k++)
  1382. {
  1383. if (layers[j1]->bottoms[0] == layers[j0]->tops[k] || layers[j1]->bottoms[1] == layers[j0]->tops[k])
  1384. {
  1385. split_top_blob_index = k;
  1386. break;
  1387. }
  1388. }
  1389. if (split_top_blob_index != -1)
  1390. break;
  1391. }
  1392. if (j1 == layer_count)
  1393. continue;
  1394. // fuse MemoryData - Split - BinaryOp to BinaryOp
  1395. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[i];
  1396. ncnn::Split* split = (ncnn::Split*)layers[j0];
  1397. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j1];
  1398. if (memorydata->w != 1 || memorydata->h != 0 || memorydata->c != 0)
  1399. {
  1400. // not a scalar
  1401. continue;
  1402. }
  1403. int memorydata_index = 1;
  1404. if (binaryop->bottoms[0] == split->tops[split_top_blob_index])
  1405. {
  1406. int op_type = binaryop->op_type;
  1407. if (op_type == ncnn::BinaryOp::Operation_ADD
  1408. || op_type == ncnn::BinaryOp::Operation_MUL
  1409. || op_type == ncnn::BinaryOp::Operation_MAX
  1410. || op_type == ncnn::BinaryOp::Operation_MIN)
  1411. {
  1412. memorydata_index = 0;
  1413. }
  1414. else if (op_type == ncnn::BinaryOp::Operation_SUB)
  1415. {
  1416. binaryop->op_type = ncnn::BinaryOp::Operation_RSUB;
  1417. memorydata_index = 0;
  1418. }
  1419. else if (op_type == ncnn::BinaryOp::Operation_DIV)
  1420. {
  1421. binaryop->op_type = ncnn::BinaryOp::Operation_RDIV;
  1422. memorydata_index = 0;
  1423. }
  1424. else
  1425. {
  1426. // non interchangeable binaryop
  1427. continue;
  1428. }
  1429. }
  1430. float scalar = memorydata->data[0];
  1431. binaryop->with_scalar = 1;
  1432. binaryop->b = scalar;
  1433. fprintf(stderr, "fuse_memorydata_binaryop %s %s\n", memorydata->name.c_str(), binaryop->name.c_str());
  1434. binaryop->bottoms.erase(binaryop->bottoms.begin() + memorydata_index);
  1435. split->tops.erase(split->tops.begin() + split_top_blob_index);
  1436. if (split->tops.empty())
  1437. {
  1438. split->type = "ncnnfused";
  1439. memorydata->type = "ncnnfused";
  1440. }
  1441. i--;
  1442. }
  1443. return 0;
  1444. }
  1445. int NetOptimize::fuse_binaryop_eltwise()
  1446. {
  1447. const size_t layer_count = layers.size();
  1448. for (size_t i = 0; i < layer_count; i++)
  1449. {
  1450. if (layers[i]->type != "BinaryOp")
  1451. continue;
  1452. if (layers[i]->bottoms.size() != 2)
  1453. continue;
  1454. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[i];
  1455. if (binaryop->op_type != ncnn::BinaryOp::Operation_ADD)
  1456. continue;
  1457. if (binaryop->with_scalar)
  1458. continue;
  1459. // BinaryOp - BinaryOp - BinaryOp
  1460. int bottom_blob_index_0 = binaryop->bottoms[0];
  1461. int bottom_blob_index_1 = binaryop->bottoms[1];
  1462. size_t j0 = 0;
  1463. for (; j0 < i; j0++)
  1464. {
  1465. if (layers[j0]->type != "BinaryOp")
  1466. continue;
  1467. if (layers[j0]->bottoms.size() != 1)
  1468. continue;
  1469. if (((ncnn::BinaryOp*)layers[j0])->op_type != ncnn::BinaryOp::Operation_MUL)
  1470. continue;
  1471. if (layers[j0]->tops[0] == bottom_blob_index_0)
  1472. break;
  1473. }
  1474. size_t j1 = 0;
  1475. for (; j1 < i; j1++)
  1476. {
  1477. if (layers[j1]->type != "BinaryOp")
  1478. continue;
  1479. if (layers[j1]->bottoms.size() != 1)
  1480. continue;
  1481. if (((ncnn::BinaryOp*)layers[j1])->op_type != ncnn::BinaryOp::Operation_MUL)
  1482. continue;
  1483. if (layers[j1]->tops[0] == bottom_blob_index_1)
  1484. break;
  1485. }
  1486. if (j0 == i && j1 == i)
  1487. continue;
  1488. ncnn::BinaryOp* binaryop0 = (ncnn::BinaryOp*)layers[j0];
  1489. ncnn::BinaryOp* binaryop1 = (ncnn::BinaryOp*)layers[j1];
  1490. fprintf(stderr, "fuse_binaryop_eltwise %s %s %s\n", binaryop0->name.c_str(), binaryop1->name.c_str(), binaryop->name.c_str());
  1491. ncnn::Eltwise* eltwise = (ncnn::Eltwise*)ncnn::create_layer("Eltwise");
  1492. eltwise->type = "Eltwise";
  1493. eltwise->name = binaryop->name;
  1494. eltwise->bottoms = binaryop->bottoms;
  1495. eltwise->tops = binaryop->tops;
  1496. ncnn::ParamDict pd;
  1497. eltwise->load_param(pd);
  1498. eltwise->op_type = ncnn::Eltwise::Operation_SUM;
  1499. eltwise->coeffs = ncnn::Mat(2);
  1500. if (j0 != i && j1 != i)
  1501. {
  1502. // fuse BinaryOp - BinaryOp - BinaryOp to Eltwise
  1503. eltwise->coeffs[0] = binaryop0->b;
  1504. eltwise->coeffs[1] = binaryop1->b;
  1505. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1506. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1507. binaryop0->type = "ncnnfused";
  1508. binaryop1->type = "ncnnfused";
  1509. }
  1510. if (j0 != i && j1 == i)
  1511. {
  1512. // fuse BinaryOp - X - BinaryOp to Eltwise
  1513. eltwise->coeffs[0] = binaryop0->b;
  1514. eltwise->coeffs[1] = 1.f;
  1515. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1516. binaryop0->type = "ncnnfused";
  1517. }
  1518. if (j0 == i && j1 != i)
  1519. {
  1520. // fuse X - BinaryOp - BinaryOp to Eltwise
  1521. eltwise->coeffs[0] = 1.f;
  1522. eltwise->coeffs[1] = binaryop1->b;
  1523. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1524. binaryop1->type = "ncnnfused";
  1525. }
  1526. layers[i] = eltwise;
  1527. delete binaryop;
  1528. }
  1529. return 0;
  1530. }
  1531. int NetOptimize::eliminate_dropout()
  1532. {
  1533. const size_t layer_count = layers.size();
  1534. for (size_t i = 0; i < layer_count; i++)
  1535. {
  1536. if (layers[i]->type != "Dropout")
  1537. continue;
  1538. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[i];
  1539. if (dropout->scale != 1.f)
  1540. continue;
  1541. // Any - Dropout
  1542. int bottom_blob_index = layers[i]->bottoms[0];
  1543. int j = i - 1;
  1544. for (; j >= 0; j--)
  1545. {
  1546. if (layers[j]->type == "ncnnfused")
  1547. continue;
  1548. if (layers[j]->tops.size() != 1)
  1549. continue;
  1550. if (layers[j]->tops[0] == bottom_blob_index)
  1551. break;
  1552. }
  1553. if (j == -1)
  1554. continue;
  1555. ncnn::Layer* any = layers[j];
  1556. fprintf(stderr, "eliminate_dropout %s %s\n", any->name.c_str(), dropout->name.c_str());
  1557. int top_blob_index_final = dropout->tops[0];
  1558. any->tops[0] = top_blob_index_final;
  1559. blobs[top_blob_index_final].producer = j;
  1560. dropout->type = "ncnnfused";
  1561. }
  1562. return 0;
  1563. }
  1564. int NetOptimize::eliminate_pooling1x1()
  1565. {
  1566. const size_t layer_count = layers.size();
  1567. for (size_t i = 0; i < layer_count; i++)
  1568. {
  1569. if (layers[i]->type != "Pooling")
  1570. continue;
  1571. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1572. if (pooling->pad_left != 0 || pooling->pad_right != 0 || pooling->pad_top != 0 || pooling->pad_bottom != 0)
  1573. continue;
  1574. if (pooling->kernel_w != 1 || pooling->kernel_h != 1 || pooling->stride_w != 1 || pooling->stride_h != 1)
  1575. continue;
  1576. if (pooling->global_pooling != 0)
  1577. continue;
  1578. // Any - Pooling
  1579. int bottom_blob_index = layers[i]->bottoms[0];
  1580. int top_i = -1;
  1581. int j = i - 1;
  1582. for (; j >= 0; j--)
  1583. {
  1584. if (layers[j]->type == "ncnnfused")
  1585. continue;
  1586. for (size_t k = 0; k < layers[j]->tops.size(); k++)
  1587. {
  1588. if (layers[j]->tops[k] == bottom_blob_index)
  1589. {
  1590. top_i = k;
  1591. break;
  1592. }
  1593. }
  1594. if (top_i != -1)
  1595. break;
  1596. }
  1597. if (j == -1)
  1598. continue;
  1599. ncnn::Layer* any = layers[j];
  1600. fprintf(stderr, "eliminate_pooling1x1 %s %s\n", any->name.c_str(), pooling->name.c_str());
  1601. int top_blob_index_final = pooling->tops[0];
  1602. any->tops[top_i] = top_blob_index_final;
  1603. blobs[top_blob_index_final].producer = j;
  1604. pooling->type = "ncnnfused";
  1605. }
  1606. return 0;
  1607. }
  1608. int NetOptimize::eliminate_noop()
  1609. {
  1610. const size_t layer_count = layers.size();
  1611. for (size_t i = 0; i < layer_count; i++)
  1612. {
  1613. if (layers[i]->type != "Noop")
  1614. continue;
  1615. ncnn::Layer* noop = layers[i];
  1616. if (noop->bottoms.empty())
  1617. {
  1618. // Noop
  1619. fprintf(stderr, "eliminate_noop %s\n", noop->name.c_str());
  1620. size_t top_blob_count = noop->tops.size();
  1621. for (size_t k = 0; k < top_blob_count; k++)
  1622. {
  1623. int top_blob_index_final = noop->tops[k];
  1624. blobs[top_blob_index_final].producer = -1;
  1625. }
  1626. noop->type = "ncnnfused";
  1627. continue;
  1628. }
  1629. // Any - Noop
  1630. int bottom_blob_index = layers[i]->bottoms[0];
  1631. int j = i - 1;
  1632. for (; j >= 0; j--)
  1633. {
  1634. if (layers[j]->type == "ncnnfused")
  1635. continue;
  1636. if (layers[j]->tops.size() != 1)
  1637. continue;
  1638. if (layers[j]->tops[0] == bottom_blob_index)
  1639. break;
  1640. }
  1641. if (j == -1)
  1642. continue;
  1643. ncnn::Layer* any = layers[j];
  1644. fprintf(stderr, "eliminate_noop %s %s\n", any->name.c_str(), noop->name.c_str());
  1645. size_t top_blob_count = std::min(noop->tops.size(), any->tops.size());
  1646. for (size_t k = 0; k < top_blob_count; k++)
  1647. {
  1648. int top_blob_index_final = noop->tops[k];
  1649. any->tops[k] = top_blob_index_final;
  1650. blobs[top_blob_index_final].producer = j;
  1651. }
  1652. noop->type = "ncnnfused";
  1653. }
  1654. return 0;
  1655. }
  1656. int NetOptimize::eliminate_orphaned_memorydata()
  1657. {
  1658. const size_t layer_count = layers.size();
  1659. for (size_t i = 0; i < layer_count; i++)
  1660. {
  1661. if (layers[i]->type != "MemoryData")
  1662. continue;
  1663. // MemoryData - X
  1664. int top_blob_index = layers[i]->tops[0];
  1665. size_t j = i + 1;
  1666. for (; j < layer_count; j++)
  1667. {
  1668. if (layers[j]->type == "ncnnfused")
  1669. continue;
  1670. bool orphaned = true;
  1671. for (size_t k = 0; k < layers[j]->bottoms.size(); k++)
  1672. {
  1673. if (layers[j]->bottoms[k] == top_blob_index)
  1674. {
  1675. orphaned = false;
  1676. break;
  1677. }
  1678. }
  1679. if (!orphaned)
  1680. break;
  1681. }
  1682. if (j < layer_count)
  1683. continue;
  1684. // assert orphaned == true
  1685. fprintf(stderr, "eliminate_orphaned_memorydata %s\n", layers[i]->name.c_str());
  1686. layers[i]->type = "ncnnfused";
  1687. }
  1688. return 0;
  1689. }
  1690. int NetOptimize::eliminate_reshape_after_global_pooling()
  1691. {
  1692. const size_t layer_count = layers.size();
  1693. for (size_t i = 0; i < layer_count; i++)
  1694. {
  1695. if (layers[i]->type != "Pooling")
  1696. continue;
  1697. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1698. if (pooling->global_pooling == 0)
  1699. continue;
  1700. // Pooling - Reshape
  1701. int top_blob_index = layers[i]->tops[0];
  1702. size_t j = i + 1;
  1703. for (; j < layer_count; j++)
  1704. {
  1705. if (layers[j]->type != "Reshape")
  1706. continue;
  1707. if (layers[j]->bottoms.size() != 1)
  1708. continue;
  1709. if (layers[j]->bottoms[0] == top_blob_index)
  1710. break;
  1711. }
  1712. if (j == layer_count)
  1713. continue;
  1714. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[j];
  1715. if (reshape->h != -233 || reshape->c != -233 || reshape->permute != 0)
  1716. continue;
  1717. fprintf(stderr, "eliminate_reshape_after_global_pooling %s %s\n", pooling->name.c_str(), reshape->name.c_str());
  1718. int top_blob_index_final = reshape->tops[0];
  1719. pooling->tops[0] = top_blob_index_final;
  1720. blobs[top_blob_index_final].producer = i;
  1721. reshape->type = "ncnnfused";
  1722. }
  1723. return 0;
  1724. }
  1725. int NetOptimize::eliminate_flatten_after_global_pooling()
  1726. {
  1727. const size_t layer_count = layers.size();
  1728. for (size_t i = 0; i < layer_count; i++)
  1729. {
  1730. if (layers[i]->type != "Pooling")
  1731. continue;
  1732. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1733. if (pooling->global_pooling == 0)
  1734. continue;
  1735. // Pooling - Flatten
  1736. int top_blob_index = layers[i]->tops[0];
  1737. size_t j = i + 1;
  1738. for (; j < layer_count; j++)
  1739. {
  1740. if (layers[j]->type != "Flatten")
  1741. continue;
  1742. if (layers[j]->bottoms.size() != 1)
  1743. continue;
  1744. if (layers[j]->bottoms[0] == top_blob_index)
  1745. break;
  1746. }
  1747. if (j == layer_count)
  1748. continue;
  1749. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1750. fprintf(stderr, "eliminate_flatten_after_global_pooling %s %s\n", pooling->name.c_str(), flatten->name.c_str());
  1751. int top_blob_index_final = flatten->tops[0];
  1752. pooling->tops[0] = top_blob_index_final;
  1753. blobs[top_blob_index_final].producer = i;
  1754. flatten->type = "ncnnfused";
  1755. }
  1756. return 0;
  1757. }
  1758. int NetOptimize::eliminate_flatten_after_innerproduct()
  1759. {
  1760. const size_t layer_count = layers.size();
  1761. for (size_t i = 0; i < layer_count; i++)
  1762. {
  1763. if (layers[i]->type != "InnerProduct")
  1764. continue;
  1765. // InnerProduct - Flatten
  1766. int top_blob_index = layers[i]->tops[0];
  1767. size_t j = i + 1;
  1768. for (; j < layer_count; j++)
  1769. {
  1770. if (layers[j]->type != "Flatten")
  1771. continue;
  1772. if (layers[j]->bottoms.size() != 1)
  1773. continue;
  1774. if (layers[j]->bottoms[0] == top_blob_index)
  1775. break;
  1776. }
  1777. if (j == layer_count)
  1778. continue;
  1779. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1780. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1781. fprintf(stderr, "eliminate_flatten_after_innerproduct %s %s\n", innerproduct->name.c_str(), flatten->name.c_str());
  1782. int top_blob_index_final = flatten->tops[0];
  1783. innerproduct->tops[0] = top_blob_index_final;
  1784. blobs[top_blob_index_final].producer = i;
  1785. flatten->type = "ncnnfused";
  1786. }
  1787. return 0;
  1788. }
  1789. int NetOptimize::eliminate_reshape_before_binaryop()
  1790. {
  1791. const size_t layer_count = layers.size();
  1792. for (size_t i = 0; i < layer_count; i++)
  1793. {
  1794. if (layers[i]->type != "Reshape")
  1795. continue;
  1796. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[i];
  1797. if (reshape->w != 1 || reshape->h != 1 || reshape->permute != 0)
  1798. continue;
  1799. // Reshape - BinaryOp
  1800. int top_blob_index = layers[i]->tops[0];
  1801. size_t j = i + 1;
  1802. for (; j < layer_count; j++)
  1803. {
  1804. if (layers[j]->type != "BinaryOp")
  1805. continue;
  1806. if (layers[j]->bottoms.size() != 2)
  1807. continue;
  1808. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1809. break;
  1810. }
  1811. if (j == layer_count)
  1812. continue;
  1813. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1814. fprintf(stderr, "eliminate_reshape_before_binaryop %s %s\n", reshape->name.c_str(), binaryop->name.c_str());
  1815. int bottom_blob_index_final = reshape->bottoms[0];
  1816. if (layers[j]->bottoms[0] == top_blob_index)
  1817. binaryop->bottoms[0] = bottom_blob_index_final;
  1818. if (layers[j]->bottoms[1] == top_blob_index)
  1819. binaryop->bottoms[1] = bottom_blob_index_final;
  1820. blobs[bottom_blob_index_final].consumer = j;
  1821. reshape->type = "ncnnfused";
  1822. }
  1823. return 0;
  1824. }
  1825. int NetOptimize::replace_reduction_with_global_pooling()
  1826. {
  1827. const size_t layer_count = layers.size();
  1828. for (size_t i = 0; i < layer_count; i++)
  1829. {
  1830. if (layers[i]->type != "Reduction")
  1831. continue;
  1832. ncnn::Reduction* reduction1 = (ncnn::Reduction*)layers[i];
  1833. if (reduction1->operation != 3 || reduction1->reduce_all != 0 || reduction1->coeff != 1.f)
  1834. continue;
  1835. if (reduction1->axes.w != 1)
  1836. continue;
  1837. const int* axes_ptr = reduction1->axes;
  1838. if (axes_ptr[0] != 2 && axes_ptr[0] != 3)
  1839. continue;
  1840. // Reduction(2/3) - Reduction(2)
  1841. int top_blob_index = layers[i]->tops[0];
  1842. size_t j = i + 1;
  1843. for (; j < layer_count; j++)
  1844. {
  1845. if (layers[j]->type != "Reduction")
  1846. continue;
  1847. if (layers[j]->bottoms.size() != 1)
  1848. continue;
  1849. if (layers[j]->bottoms[0] == top_blob_index)
  1850. break;
  1851. }
  1852. if (j == layer_count)
  1853. continue;
  1854. ncnn::Reduction* reduction2 = (ncnn::Reduction*)layers[j];
  1855. if (reduction2->operation != 3 || reduction2->reduce_all != 0 || reduction2->coeff != 1.f)
  1856. continue;
  1857. if (reduction2->axes.w != 1)
  1858. continue;
  1859. const int* axes2_ptr = reduction2->axes;
  1860. if (axes2_ptr[0] != 2)
  1861. continue;
  1862. fprintf(stderr, "replace_reduction_with_global_pooling %s %s\n", reduction1->name.c_str(), reduction2->name.c_str());
  1863. ncnn::Pooling* pooling = (ncnn::Pooling*)ncnn::create_layer("Pooling");
  1864. pooling->type = "Pooling";
  1865. pooling->name = reduction2->name;
  1866. pooling->bottoms = reduction2->bottoms;
  1867. pooling->tops = reduction2->tops;
  1868. ncnn::ParamDict pd;
  1869. pooling->load_param(pd);
  1870. pooling->pooling_type = 1;
  1871. pooling->global_pooling = 1;
  1872. layers[j] = pooling;
  1873. delete reduction2;
  1874. int bottom_blob_index_final = reduction1->bottoms[0];
  1875. pooling->bottoms[0] = bottom_blob_index_final;
  1876. blobs[bottom_blob_index_final].consumer = j;
  1877. reduction1->type = "ncnnfused";
  1878. }
  1879. return 0;
  1880. }
  1881. int NetOptimize::replace_prelu_with_leaky_relu()
  1882. {
  1883. const size_t layer_count = layers.size();
  1884. for (size_t i = 0; i < layer_count; i++)
  1885. {
  1886. if (layers[i]->type != "PReLU")
  1887. continue;
  1888. ncnn::PReLU* prelu = (ncnn::PReLU*)layers[i];
  1889. if (prelu->num_slope != 1)
  1890. continue;
  1891. fprintf(stderr, "replace_prelu_with_leaky_relu %s\n", prelu->name.c_str());
  1892. ncnn::ReLU* relu = (ncnn::ReLU*)ncnn::create_layer("ReLU");
  1893. relu->type = "ReLU";
  1894. relu->name = prelu->name;
  1895. relu->bottoms = prelu->bottoms;
  1896. relu->tops = prelu->tops;
  1897. ncnn::ParamDict pd;
  1898. relu->load_param(pd);
  1899. relu->slope = prelu->slope_data[0];
  1900. layers[i] = relu;
  1901. delete prelu;
  1902. }
  1903. return 0;
  1904. }
  1905. int NetOptimize::replace_convolution_with_innerproduct_after_global_pooling()
  1906. {
  1907. const size_t layer_count = layers.size();
  1908. for (size_t i = 0; i < layer_count; i++)
  1909. {
  1910. if (layers[i]->type != "Pooling")
  1911. continue;
  1912. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1913. if (pooling->global_pooling == 0)
  1914. continue;
  1915. // Pooling - Convolution
  1916. int top_blob_index = layers[i]->tops[0];
  1917. size_t j = i + 1;
  1918. for (; j < layer_count; j++)
  1919. {
  1920. if (layers[j]->type != "Convolution")
  1921. continue;
  1922. if (layers[j]->bottoms.size() != 1)
  1923. continue;
  1924. if (layers[j]->bottoms[0] == top_blob_index)
  1925. break;
  1926. }
  1927. if (j == layer_count)
  1928. continue;
  1929. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  1930. fprintf(stderr, "replace_convolution_with_innerproduct_after_global_pooling %s %s\n", pooling->name.c_str(), convolution->name.c_str());
  1931. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  1932. innerproduct->type = "InnerProduct";
  1933. innerproduct->name = convolution->name;
  1934. innerproduct->bottoms = convolution->bottoms;
  1935. innerproduct->tops = convolution->tops;
  1936. ncnn::ParamDict pd;
  1937. innerproduct->load_param(pd);
  1938. innerproduct->num_output = convolution->num_output;
  1939. innerproduct->bias_term = convolution->bias_term;
  1940. innerproduct->weight_data_size = convolution->weight_data_size;
  1941. innerproduct->int8_scale_term = convolution->int8_scale_term;
  1942. innerproduct->weight_data = convolution->weight_data;
  1943. innerproduct->bias_data = convolution->bias_data;
  1944. #if NCNN_INT8
  1945. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  1946. innerproduct->bottom_blob_int8_scales = convolution->bottom_blob_int8_scales;
  1947. #endif
  1948. innerproduct->activation_type = convolution->activation_type;
  1949. innerproduct->activation_params = convolution->activation_params;
  1950. layers[j] = innerproduct;
  1951. delete convolution;
  1952. }
  1953. return 0;
  1954. }
  1955. int NetOptimize::replace_convolution_with_innerproduct_after_innerproduct()
  1956. {
  1957. const size_t layer_count = layers.size();
  1958. for (;;)
  1959. {
  1960. bool replaced = false;
  1961. for (size_t i = 0; i < layer_count; i++)
  1962. {
  1963. if (layers[i]->type != "InnerProduct")
  1964. continue;
  1965. // InnerProduct - Convolution
  1966. int top_blob_index = layers[i]->tops[0];
  1967. size_t j = i + 1;
  1968. for (; j < layer_count; j++)
  1969. {
  1970. if (layers[j]->type != "Convolution")
  1971. continue;
  1972. if (layers[j]->bottoms.size() != 1)
  1973. continue;
  1974. if (layers[j]->bottoms[0] == top_blob_index)
  1975. break;
  1976. }
  1977. if (j == layer_count)
  1978. continue;
  1979. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1980. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  1981. fprintf(stderr, "replace_convolution_with_innerproduct_after_innerproduct %s %s\n", innerproduct->name.c_str(), convolution->name.c_str());
  1982. ncnn::InnerProduct* innerproduct2 = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  1983. innerproduct2->type = "InnerProduct";
  1984. innerproduct2->name = convolution->name;
  1985. innerproduct2->bottoms = convolution->bottoms;
  1986. innerproduct2->tops = convolution->tops;
  1987. ncnn::ParamDict pd;
  1988. innerproduct2->load_param(pd);
  1989. innerproduct2->num_output = convolution->num_output;
  1990. innerproduct2->bias_term = convolution->bias_term;
  1991. innerproduct2->weight_data_size = convolution->weight_data_size;
  1992. innerproduct->int8_scale_term = convolution->int8_scale_term;
  1993. innerproduct2->weight_data = convolution->weight_data;
  1994. innerproduct2->bias_data = convolution->bias_data;
  1995. #if NCNN_INT8
  1996. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  1997. innerproduct->bottom_blob_int8_scales = convolution->bottom_blob_int8_scales;
  1998. #endif
  1999. innerproduct2->activation_type = convolution->activation_type;
  2000. innerproduct2->activation_params = convolution->activation_params;
  2001. layers[j] = innerproduct2;
  2002. delete convolution;
  2003. replaced = true;
  2004. }
  2005. if (!replaced)
  2006. break;
  2007. }
  2008. return 0;
  2009. }
  2010. int main(int argc, char** argv)
  2011. {
  2012. if (argc < 6)
  2013. {
  2014. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag] [cutstart] [cutend]\n", argv[0]);
  2015. return -1;
  2016. }
  2017. const char* inparam = argv[1];
  2018. const char* inbin = argv[2];
  2019. const char* outparam = argv[3];
  2020. const char* outbin = argv[4];
  2021. int flag = atoi(argv[5]);
  2022. const char* cutstartname = nullptr;
  2023. const char* cutendname = nullptr;
  2024. if (argc > 6)
  2025. {
  2026. cutstartname = argv[6];
  2027. }
  2028. if (argc > 7)
  2029. {
  2030. cutendname = argv[7];
  2031. }
  2032. NetOptimize optimizer;
  2033. if (flag == 65536 || flag == 1)
  2034. {
  2035. optimizer.storage_type = 1;
  2036. }
  2037. else
  2038. {
  2039. optimizer.storage_type = 0;
  2040. }
  2041. optimizer.load_param(inparam);
  2042. if (strcmp(inbin, "null") == 0)
  2043. {
  2044. DataReaderFromEmpty dr;
  2045. optimizer.load_model(dr);
  2046. }
  2047. else
  2048. optimizer.load_model(inbin);
  2049. if (optimizer.set_cutparam(cutstartname, cutendname) < 0)
  2050. {
  2051. return -1;
  2052. }
  2053. optimizer.fuse_batchnorm_scale();
  2054. optimizer.fuse_convolution_batchnorm();
  2055. optimizer.fuse_convolution_mul();
  2056. optimizer.fuse_convolution_add();
  2057. optimizer.fuse_convolutiondepthwise_batchnorm();
  2058. optimizer.fuse_convolutiondepthwise_mul();
  2059. optimizer.fuse_convolutiondepthwise_add();
  2060. optimizer.fuse_deconvolution_batchnorm();
  2061. optimizer.fuse_deconvolution_mul();
  2062. optimizer.fuse_deconvolution_add();
  2063. optimizer.fuse_deconvolutiondepthwise_batchnorm();
  2064. optimizer.fuse_innerproduct_batchnorm();
  2065. optimizer.fuse_innerproduct_add();
  2066. optimizer.fuse_innerproduct_dropout();
  2067. optimizer.replace_reduction_with_global_pooling();
  2068. optimizer.replace_prelu_with_leaky_relu();
  2069. optimizer.fuse_convolution_activation();
  2070. optimizer.fuse_convolutiondepthwise_activation();
  2071. optimizer.fuse_deconvolution_activation();
  2072. optimizer.fuse_deconvolutiondepthwise_activation();
  2073. optimizer.fuse_innerproduct_activation();
  2074. optimizer.fuse_memorydata_binaryop();
  2075. optimizer.fuse_binaryop_eltwise();
  2076. optimizer.eliminate_dropout();
  2077. optimizer.eliminate_pooling1x1();
  2078. optimizer.eliminate_noop();
  2079. optimizer.eliminate_flatten_after_global_pooling();
  2080. optimizer.eliminate_reshape_after_global_pooling();
  2081. optimizer.eliminate_reshape_before_binaryop();
  2082. optimizer.replace_convolution_with_innerproduct_after_global_pooling();
  2083. optimizer.replace_convolution_with_innerproduct_after_innerproduct();
  2084. optimizer.eliminate_flatten_after_innerproduct();
  2085. optimizer.eliminate_orphaned_memorydata();
  2086. optimizer.shape_inference();
  2087. optimizer.estimate_memory_footprint();
  2088. optimizer.save(outparam, outbin);
  2089. return 0;
  2090. }