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

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