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