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