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