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