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

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