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