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