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

6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920
  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 <map>
  19. #include <set>
  20. #include <vector>
  21. // ncnn public header
  22. #include "datareader.h"
  23. #include "layer.h"
  24. #include "net.h"
  25. // ncnn private header
  26. #include "layer/batchnorm.h"
  27. #include "layer/bias.h"
  28. #include "layer/binaryop.h"
  29. #include "layer/clip.h"
  30. #include "layer/concat.h"
  31. #include "layer/convolution.h"
  32. #include "layer/convolutiondepthwise.h"
  33. #include "layer/crop.h"
  34. #include "layer/deconvolution.h"
  35. #include "layer/deconvolutiondepthwise.h"
  36. #include "layer/detectionoutput.h"
  37. #include "layer/dropout.h"
  38. #include "layer/eltwise.h"
  39. #include "layer/elu.h"
  40. #include "layer/exp.h"
  41. #include "layer/expanddims.h"
  42. #include "layer/flatten.h"
  43. #include "layer/gemm.h"
  44. #include "layer/groupnorm.h"
  45. #include "layer/hardsigmoid.h"
  46. #include "layer/hardswish.h"
  47. #include "layer/innerproduct.h"
  48. #include "layer/input.h"
  49. #include "layer/instancenorm.h"
  50. #include "layer/interp.h"
  51. #include "layer/log.h"
  52. #include "layer/lrn.h"
  53. #include "layer/lstm.h"
  54. #include "layer/memorydata.h"
  55. #include "layer/mvn.h"
  56. #include "layer/normalize.h"
  57. #include "layer/padding.h"
  58. #include "layer/permute.h"
  59. #include "layer/pixelshuffle.h"
  60. #include "layer/pooling.h"
  61. #include "layer/power.h"
  62. #include "layer/prelu.h"
  63. #include "layer/priorbox.h"
  64. #include "layer/proposal.h"
  65. #include "layer/psroipooling.h"
  66. #include "layer/quantize.h"
  67. #include "layer/reduction.h"
  68. #include "layer/relu.h"
  69. #include "layer/reorg.h"
  70. #include "layer/requantize.h"
  71. #include "layer/reshape.h"
  72. #include "layer/roialign.h"
  73. #include "layer/roipooling.h"
  74. #include "layer/scale.h"
  75. #include "layer/shufflechannel.h"
  76. #include "layer/slice.h"
  77. #include "layer/softmax.h"
  78. #include "layer/split.h"
  79. #include "layer/squeeze.h"
  80. #include "layer/threshold.h"
  81. #include "layer/unaryop.h"
  82. #include "layer/yolodetectionoutput.h"
  83. #include "layer/yolov3detectionoutput.h"
  84. class DataReaderFromEmpty : public ncnn::DataReader
  85. {
  86. public:
  87. virtual int scan(const char* format, void* p) const
  88. {
  89. return 0;
  90. }
  91. virtual size_t read(void* /*buf*/, size_t size) const
  92. {
  93. return size;
  94. }
  95. };
  96. class MemoryFootprintAllocator : public ncnn::Allocator
  97. {
  98. public:
  99. MemoryFootprintAllocator()
  100. {
  101. current_memory_usage = 0;
  102. memory_footprint = 0;
  103. }
  104. virtual void* fastMalloc(size_t size)
  105. {
  106. ncnn::MutexLockGuard g(lock);
  107. void* ptr = ncnn::fastMalloc(size);
  108. bookkeeper[ptr] = size;
  109. current_memory_usage += size;
  110. memory_footprint = std::max(memory_footprint, current_memory_usage);
  111. return ptr;
  112. }
  113. virtual void fastFree(void* ptr)
  114. {
  115. ncnn::MutexLockGuard g(lock);
  116. size_t size = bookkeeper[ptr];
  117. current_memory_usage -= size;
  118. bookkeeper.erase(bookkeeper.find(ptr));
  119. ncnn::fastFree(ptr);
  120. }
  121. public:
  122. int current_memory_usage;
  123. int memory_footprint;
  124. ncnn::Mutex lock;
  125. std::map<void*, size_t> bookkeeper;
  126. };
  127. class NetOptimize : public ncnn::Net
  128. {
  129. public:
  130. // 0=fp32 1=fp16
  131. int storage_type;
  132. public:
  133. int fuse_batchnorm_scale();
  134. int fuse_convolution_batchnorm();
  135. int fuse_convolution_mul();
  136. int fuse_convolution_add();
  137. int fuse_convolutiondepthwise_batchnorm();
  138. int fuse_convolutiondepthwise_mul();
  139. int fuse_convolutiondepthwise_add();
  140. int fuse_deconvolution_batchnorm();
  141. int fuse_deconvolution_mul();
  142. int fuse_deconvolution_add();
  143. int fuse_deconvolutiondepthwise_batchnorm();
  144. int fuse_innerproduct_batchnorm();
  145. int fuse_innerproduct_add();
  146. int fuse_innerproduct_dropout();
  147. int fuse_convolution_activation();
  148. int fuse_convolutiondepthwise_activation();
  149. int fuse_deconvolution_activation();
  150. int fuse_deconvolutiondepthwise_activation();
  151. int fuse_innerproduct_activation();
  152. int fuse_memorydata_binaryop();
  153. int fuse_binaryop_eltwise();
  154. int eliminate_dropout();
  155. int eliminate_pooling1x1();
  156. int eliminate_noop();
  157. int eliminate_orphaned_memorydata();
  158. int eliminate_flatten_after_global_pooling();
  159. int eliminate_reshape_after_global_pooling();
  160. int eliminate_flatten_after_innerproduct();
  161. int eliminate_reshape_before_binaryop();
  162. int replace_reduction_with_global_pooling();
  163. int replace_prelu_with_leaky_relu();
  164. int replace_convolution_with_innerproduct_after_global_pooling();
  165. int replace_convolution_with_innerproduct_after_innerproduct();
  166. int shape_inference();
  167. int estimate_memory_footprint();
  168. public:
  169. int fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp);
  170. int fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp);
  171. int fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp);
  172. int fwrite_weight_data(const ncnn::Mat& data, FILE* bp);
  173. int save(const char* parampath, const char* binpath);
  174. };
  175. int NetOptimize::fuse_batchnorm_scale()
  176. {
  177. const size_t layer_count = layers.size();
  178. for (size_t i = 0; i < layer_count; i++)
  179. {
  180. if (layers[i]->type != "BatchNorm")
  181. continue;
  182. // BatchNorm - Scale
  183. int top_blob_index = layers[i]->tops[0];
  184. size_t j = i + 1;
  185. for (; j < layer_count; j++)
  186. {
  187. if (layers[j]->type != "Scale")
  188. continue;
  189. if (layers[j]->bottoms.size() != 1)
  190. continue;
  191. if (layers[j]->bottoms[0] == top_blob_index)
  192. break;
  193. }
  194. if (j == layer_count)
  195. continue;
  196. // fuse BatchNorm - Scale to BatchNorm
  197. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[i];
  198. ncnn::Scale* scale = (ncnn::Scale*)layers[j];
  199. fprintf(stderr, "fuse_batchnorm_scale %s %s\n", batchnorm->name.c_str(), scale->name.c_str());
  200. {
  201. // v = ((v - mean) / sqrt(var + eps) * slope + bias) * s + b
  202. // = (v - mean) / sqrt(var + eps) * (slope * s) + (bias * s + b)
  203. int channels = batchnorm->channels;
  204. float* slope = batchnorm->slope_data;
  205. float* bias = batchnorm->bias_data;
  206. for (int q = 0; q < channels; q++)
  207. {
  208. slope[q] = slope[q] * scale->scale_data[q];
  209. if (scale->bias_term)
  210. bias[q] = bias[q] * scale->scale_data[q] + scale->bias_data[q];
  211. else
  212. bias[q] = bias[q] * scale->scale_data[q];
  213. }
  214. }
  215. int top_blob_index_final = scale->tops[0];
  216. batchnorm->tops[0] = top_blob_index_final;
  217. blobs[top_blob_index_final].producer = i;
  218. scale->type = "ncnnfused";
  219. }
  220. return 0;
  221. }
  222. int NetOptimize::fuse_convolution_batchnorm()
  223. {
  224. const size_t layer_count = layers.size();
  225. for (size_t i = 0; i < layer_count; i++)
  226. {
  227. if (layers[i]->type != "Convolution")
  228. continue;
  229. // Convolution - BatchNorm
  230. int top_blob_index = layers[i]->tops[0];
  231. size_t j = i + 1;
  232. for (; j < layer_count; j++)
  233. {
  234. if (layers[j]->type != "BatchNorm")
  235. continue;
  236. if (layers[j]->bottoms.size() != 1)
  237. continue;
  238. if (layers[j]->bottoms[0] == top_blob_index)
  239. break;
  240. }
  241. if (j == layer_count)
  242. continue;
  243. // fuse Convolution - BatchNorm to Convolution
  244. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  245. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  246. fprintf(stderr, "fuse_convolution_batchnorm %s %s\n", convolution->name.c_str(), batchnorm->name.c_str());
  247. {
  248. int channels = batchnorm->channels;
  249. float eps = batchnorm->eps;
  250. // a = bias - slope * mean / sqrt(var + eps)
  251. // b = slope / sqrt(var + eps)
  252. // value = value * b + a
  253. std::vector<float> a(channels);
  254. std::vector<float> b(channels);
  255. for (int i = 0; i < channels; i++)
  256. {
  257. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  258. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  259. b[i] = batchnorm->slope_data[i] / sqrt_var;
  260. }
  261. if (convolution->bias_term == 0)
  262. {
  263. // init bias as zero
  264. convolution->bias_term = 1;
  265. convolution->bias_data = ncnn::Mat(channels);
  266. convolution->bias_data.fill(0.f);
  267. }
  268. const int weight_per_outch = convolution->weight_data_size / channels;
  269. float* weight = convolution->weight_data;
  270. float* bias = convolution->bias_data;
  271. for (int i = 0; i < channels; i++)
  272. {
  273. float* conv_weight_outch = weight + weight_per_outch * i;
  274. for (int j = 0; j < weight_per_outch; j++)
  275. {
  276. conv_weight_outch[j] *= b[i];
  277. }
  278. bias[i] = bias[i] * b[i] + a[i];
  279. }
  280. }
  281. int top_blob_index_final = batchnorm->tops[0];
  282. convolution->tops[0] = top_blob_index_final;
  283. blobs[top_blob_index_final].producer = i;
  284. batchnorm->type = "ncnnfused";
  285. }
  286. return 0;
  287. }
  288. int NetOptimize::fuse_convolution_mul()
  289. {
  290. const size_t layer_count = layers.size();
  291. for (size_t i = 0; i < layer_count; i++)
  292. {
  293. if (layers[i]->type != "Convolution")
  294. continue;
  295. // Convolution - BinaryOp
  296. int top_blob_index = layers[i]->tops[0];
  297. size_t j = i + 1;
  298. for (; j < layer_count; j++)
  299. {
  300. if (layers[j]->type != "BinaryOp")
  301. continue;
  302. if (layers[j]->bottoms.size() != 2)
  303. continue;
  304. if (layers[j]->bottoms[0] == top_blob_index)
  305. break;
  306. }
  307. if (j == layer_count)
  308. continue;
  309. // fuse Convolution - BinaryOp to Convolution
  310. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  311. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  312. if (binaryop->op_type != 2 || binaryop->with_scalar)
  313. continue;
  314. // MemoryData - ..... - BinaryOp
  315. size_t k = 0;
  316. for (; k < j; k++)
  317. {
  318. if (layers[k]->type != "MemoryData")
  319. continue;
  320. if (layers[k]->tops[0] == binaryop->bottoms[1])
  321. break;
  322. }
  323. if (k == j)
  324. continue;
  325. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  326. int channels = convolution->num_output;
  327. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  328. {
  329. // not bias-like broadcasting type
  330. continue;
  331. }
  332. fprintf(stderr, "fuse_convolution_mul %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
  333. {
  334. const int weight_per_outch = convolution->weight_data_size / channels;
  335. float* weight = convolution->weight_data;
  336. float* bias = convolution->bias_data;
  337. for (int i = 0; i < channels; i++)
  338. {
  339. float* conv_weight_outch = weight + weight_per_outch * i;
  340. for (int j = 0; j < weight_per_outch; j++)
  341. {
  342. conv_weight_outch[j] *= memorydata->data[i];
  343. }
  344. if (bias)
  345. {
  346. bias[i] = bias[i] * memorydata->data[i];
  347. }
  348. }
  349. }
  350. int top_blob_index_final = binaryop->tops[0];
  351. convolution->tops[0] = top_blob_index_final;
  352. blobs[top_blob_index_final].producer = i;
  353. binaryop->type = "ncnnfused";
  354. }
  355. return 0;
  356. }
  357. int NetOptimize::fuse_convolution_add()
  358. {
  359. const size_t layer_count = layers.size();
  360. for (size_t i = 0; i < layer_count; i++)
  361. {
  362. if (layers[i]->type != "Convolution")
  363. continue;
  364. // Convolution - BinaryOp
  365. int top_blob_index = layers[i]->tops[0];
  366. size_t j = i + 1;
  367. for (; j < layer_count; j++)
  368. {
  369. if (layers[j]->type != "BinaryOp")
  370. continue;
  371. if (layers[j]->bottoms.size() != 2)
  372. continue;
  373. if (layers[j]->bottoms[0] == top_blob_index)
  374. break;
  375. }
  376. if (j == layer_count)
  377. continue;
  378. // fuse Convolution - BinaryOp to Convolution
  379. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  380. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  381. if (binaryop->op_type != 0 || binaryop->with_scalar)
  382. continue;
  383. // MemoryData - ..... - BinaryOp
  384. size_t k = 0;
  385. for (; k < j; k++)
  386. {
  387. if (layers[k]->type != "MemoryData")
  388. continue;
  389. if (layers[k]->tops[0] == binaryop->bottoms[1])
  390. break;
  391. }
  392. if (k == j)
  393. continue;
  394. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  395. int channels = convolution->num_output;
  396. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  397. {
  398. // not bias-like broadcasting type
  399. continue;
  400. }
  401. fprintf(stderr, "fuse_convolution_add %s %s\n", convolution->name.c_str(), binaryop->name.c_str());
  402. {
  403. if (convolution->bias_term == 0)
  404. {
  405. // init bias
  406. convolution->bias_term = 1;
  407. convolution->bias_data = memorydata->data;
  408. }
  409. else
  410. {
  411. float* bias = convolution->bias_data;
  412. for (int i = 0; i < channels; i++)
  413. {
  414. bias[i] = bias[i] + memorydata->data[i];
  415. }
  416. }
  417. }
  418. int top_blob_index_final = binaryop->tops[0];
  419. convolution->tops[0] = top_blob_index_final;
  420. blobs[top_blob_index_final].producer = i;
  421. binaryop->type = "ncnnfused";
  422. }
  423. return 0;
  424. }
  425. int NetOptimize::fuse_convolutiondepthwise_batchnorm()
  426. {
  427. const size_t layer_count = layers.size();
  428. for (size_t i = 0; i < layer_count; i++)
  429. {
  430. if (layers[i]->type != "ConvolutionDepthWise")
  431. continue;
  432. // ConvolutionDepthWise - BatchNorm
  433. int top_blob_index = layers[i]->tops[0];
  434. size_t j = i + 1;
  435. for (; j < layer_count; j++)
  436. {
  437. if (layers[j]->type != "BatchNorm")
  438. continue;
  439. if (layers[j]->bottoms.size() != 1)
  440. continue;
  441. if (layers[j]->bottoms[0] == top_blob_index)
  442. break;
  443. }
  444. if (j == layer_count)
  445. continue;
  446. // fuse ConvolutionDepthWise - BatchNorm to ConvolutionDepthWise
  447. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  448. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  449. fprintf(stderr, "fuse_convolutiondepthwise_batchnorm %s %s\n", convolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  450. {
  451. int channels = batchnorm->channels;
  452. float eps = batchnorm->eps;
  453. // a = bias - slope * mean / sqrt(var + eps)
  454. // b = slope / sqrt(var + eps)
  455. // value = value * b + a
  456. std::vector<float> a(channels);
  457. std::vector<float> b(channels);
  458. for (int i = 0; i < channels; i++)
  459. {
  460. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  461. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  462. b[i] = batchnorm->slope_data[i] / sqrt_var;
  463. }
  464. if (convolutiondepthwise->bias_term == 0)
  465. {
  466. // init bias as zero
  467. convolutiondepthwise->bias_term = 1;
  468. convolutiondepthwise->bias_data = ncnn::Mat(channels);
  469. convolutiondepthwise->bias_data.fill(0.f);
  470. }
  471. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  472. float* weight = convolutiondepthwise->weight_data;
  473. float* bias = convolutiondepthwise->bias_data;
  474. for (int i = 0; i < channels; i++)
  475. {
  476. float* conv_weight_outch = weight + weight_per_outch * i;
  477. for (int j = 0; j < weight_per_outch; j++)
  478. {
  479. conv_weight_outch[j] *= b[i];
  480. }
  481. bias[i] = bias[i] * b[i] + a[i];
  482. }
  483. }
  484. int top_blob_index_final = batchnorm->tops[0];
  485. convolutiondepthwise->tops[0] = top_blob_index_final;
  486. blobs[top_blob_index_final].producer = i;
  487. batchnorm->type = "ncnnfused";
  488. }
  489. return 0;
  490. }
  491. int NetOptimize::fuse_convolutiondepthwise_mul()
  492. {
  493. const size_t layer_count = layers.size();
  494. for (size_t i = 0; i < layer_count; i++)
  495. {
  496. if (layers[i]->type != "ConvolutionDepthWise")
  497. continue;
  498. // ConvolutionDepthWise - BinaryOp
  499. int top_blob_index = layers[i]->tops[0];
  500. size_t j = i + 1;
  501. for (; j < layer_count; j++)
  502. {
  503. if (layers[j]->type != "BinaryOp")
  504. continue;
  505. if (layers[j]->bottoms.size() != 2)
  506. continue;
  507. if (layers[j]->bottoms[0] == top_blob_index)
  508. break;
  509. }
  510. if (j == layer_count)
  511. continue;
  512. // fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
  513. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  514. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  515. if (binaryop->op_type != 2 || binaryop->with_scalar)
  516. continue;
  517. // MemoryData - ..... - BinaryOp
  518. size_t k = 0;
  519. for (; k < j; k++)
  520. {
  521. if (layers[k]->type != "MemoryData")
  522. continue;
  523. if (layers[k]->tops[0] == binaryop->bottoms[1])
  524. break;
  525. }
  526. if (k == j)
  527. continue;
  528. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  529. int channels = convolutiondepthwise->num_output;
  530. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  531. {
  532. // not bias-like broadcasting type
  533. continue;
  534. }
  535. fprintf(stderr, "fuse_convolutiondepthwise_mul %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
  536. {
  537. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  538. float* weight = convolutiondepthwise->weight_data;
  539. float* bias = convolutiondepthwise->bias_data;
  540. for (int i = 0; i < channels; i++)
  541. {
  542. float* conv_weight_outch = weight + weight_per_outch * i;
  543. for (int j = 0; j < weight_per_outch; j++)
  544. {
  545. conv_weight_outch[j] *= memorydata->data[i];
  546. }
  547. if (bias)
  548. {
  549. bias[i] = bias[i] * memorydata->data[i];
  550. }
  551. }
  552. }
  553. int top_blob_index_final = binaryop->tops[0];
  554. convolutiondepthwise->tops[0] = top_blob_index_final;
  555. blobs[top_blob_index_final].producer = i;
  556. binaryop->type = "ncnnfused";
  557. }
  558. return 0;
  559. }
  560. int NetOptimize::fuse_convolutiondepthwise_add()
  561. {
  562. const size_t layer_count = layers.size();
  563. for (size_t i = 0; i < layer_count; i++)
  564. {
  565. if (layers[i]->type != "ConvolutionDepthWise")
  566. continue;
  567. // ConvolutionDepthWise - BinaryOp
  568. int top_blob_index = layers[i]->tops[0];
  569. size_t j = i + 1;
  570. for (; j < layer_count; j++)
  571. {
  572. if (layers[j]->type != "BinaryOp")
  573. continue;
  574. if (layers[j]->bottoms.size() != 2)
  575. continue;
  576. if (layers[j]->bottoms[0] == top_blob_index)
  577. break;
  578. }
  579. if (j == layer_count)
  580. continue;
  581. // fuse ConvolutionDepthWise - BinaryOp to ConvolutionDepthWise
  582. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  583. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  584. if (binaryop->op_type != 0 || binaryop->with_scalar)
  585. continue;
  586. // MemoryData - ..... - BinaryOp
  587. size_t k = 0;
  588. for (; k < j; k++)
  589. {
  590. if (layers[k]->type != "MemoryData")
  591. continue;
  592. if (layers[k]->tops[0] == binaryop->bottoms[1])
  593. break;
  594. }
  595. if (k == j)
  596. continue;
  597. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  598. int channels = convolutiondepthwise->num_output;
  599. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  600. {
  601. // not bias-like broadcasting type
  602. continue;
  603. }
  604. fprintf(stderr, "fuse_convolutiondepthwise_add %s %s\n", convolutiondepthwise->name.c_str(), binaryop->name.c_str());
  605. {
  606. if (convolutiondepthwise->bias_term == 0)
  607. {
  608. // init bias
  609. convolutiondepthwise->bias_term = 1;
  610. convolutiondepthwise->bias_data = memorydata->data;
  611. }
  612. else
  613. {
  614. float* bias = convolutiondepthwise->bias_data;
  615. for (int i = 0; i < channels; i++)
  616. {
  617. bias[i] = bias[i] + memorydata->data[i];
  618. }
  619. }
  620. }
  621. int top_blob_index_final = binaryop->tops[0];
  622. convolutiondepthwise->tops[0] = top_blob_index_final;
  623. blobs[top_blob_index_final].producer = i;
  624. binaryop->type = "ncnnfused";
  625. }
  626. return 0;
  627. }
  628. int NetOptimize::fuse_deconvolution_batchnorm()
  629. {
  630. const size_t layer_count = layers.size();
  631. for (size_t i = 0; i < layer_count; i++)
  632. {
  633. if (layers[i]->type != "Deconvolution")
  634. continue;
  635. // Deconvolution - BatchNorm
  636. int top_blob_index = layers[i]->tops[0];
  637. size_t j = i + 1;
  638. for (; j < layer_count; j++)
  639. {
  640. if (layers[j]->type != "BatchNorm")
  641. continue;
  642. if (layers[j]->bottoms.size() != 1)
  643. continue;
  644. if (layers[j]->bottoms[0] == top_blob_index)
  645. break;
  646. }
  647. if (j == layer_count)
  648. continue;
  649. // fuse Deconvolution - BatchNorm to Deconvolution
  650. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  651. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  652. fprintf(stderr, "fuse_deconvolution_batchnorm %s %s\n", deconvolution->name.c_str(), batchnorm->name.c_str());
  653. {
  654. int channels = batchnorm->channels;
  655. float eps = batchnorm->eps;
  656. // a = bias - slope * mean / sqrt(var + eps)
  657. // b = slope / sqrt(var + eps)
  658. // value = value * b + a
  659. std::vector<float> a(channels);
  660. std::vector<float> b(channels);
  661. for (int i = 0; i < channels; i++)
  662. {
  663. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  664. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  665. b[i] = batchnorm->slope_data[i] / sqrt_var;
  666. }
  667. if (deconvolution->bias_term == 0)
  668. {
  669. // init bias as zero
  670. deconvolution->bias_term = 1;
  671. deconvolution->bias_data = ncnn::Mat(channels);
  672. deconvolution->bias_data.fill(0.f);
  673. }
  674. const int weight_per_outch = deconvolution->weight_data_size / channels;
  675. float* weight = deconvolution->weight_data;
  676. float* bias = deconvolution->bias_data;
  677. for (int i = 0; i < channels; i++)
  678. {
  679. float* conv_weight_outch = weight + weight_per_outch * i;
  680. for (int j = 0; j < weight_per_outch; j++)
  681. {
  682. conv_weight_outch[j] *= b[i];
  683. }
  684. bias[i] = bias[i] * b[i] + a[i];
  685. }
  686. }
  687. int top_blob_index_final = batchnorm->tops[0];
  688. deconvolution->tops[0] = top_blob_index_final;
  689. blobs[top_blob_index_final].producer = i;
  690. batchnorm->type = "ncnnfused";
  691. }
  692. return 0;
  693. }
  694. int NetOptimize::fuse_deconvolution_mul()
  695. {
  696. const size_t layer_count = layers.size();
  697. for (size_t i = 0; i < layer_count; i++)
  698. {
  699. if (layers[i]->type != "Deconvolution")
  700. continue;
  701. // Deconvolution - BinaryOp
  702. int top_blob_index = layers[i]->tops[0];
  703. size_t j = i + 1;
  704. for (; j < layer_count; j++)
  705. {
  706. if (layers[j]->type != "BinaryOp")
  707. continue;
  708. if (layers[j]->bottoms.size() != 2)
  709. continue;
  710. if (layers[j]->bottoms[0] == top_blob_index)
  711. break;
  712. }
  713. if (j == layer_count)
  714. continue;
  715. // fuse Deconvolution - BinaryOp to Deconvolution
  716. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  717. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  718. if (binaryop->op_type != 2 || binaryop->with_scalar)
  719. continue;
  720. // MemoryData - ..... - BinaryOp
  721. size_t k = 0;
  722. for (; k < j; k++)
  723. {
  724. if (layers[k]->type != "MemoryData")
  725. continue;
  726. if (layers[k]->tops[0] == binaryop->bottoms[1])
  727. break;
  728. }
  729. if (k == j)
  730. continue;
  731. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  732. int channels = deconvolution->num_output;
  733. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  734. {
  735. // not bias-like broadcasting type
  736. continue;
  737. }
  738. fprintf(stderr, "fuse_deconvolution_mul %s %s\n", deconvolution->name.c_str(), binaryop->name.c_str());
  739. {
  740. const int weight_per_outch = deconvolution->weight_data_size / channels;
  741. float* weight = deconvolution->weight_data;
  742. float* bias = deconvolution->bias_data;
  743. for (int i = 0; i < channels; i++)
  744. {
  745. float* conv_weight_outch = weight + weight_per_outch * i;
  746. for (int j = 0; j < weight_per_outch; j++)
  747. {
  748. conv_weight_outch[j] *= memorydata->data[i];
  749. }
  750. if (bias)
  751. {
  752. bias[i] = bias[i] * memorydata->data[i];
  753. }
  754. }
  755. }
  756. int top_blob_index_final = binaryop->tops[0];
  757. deconvolution->tops[0] = top_blob_index_final;
  758. blobs[top_blob_index_final].producer = i;
  759. binaryop->type = "ncnnfused";
  760. }
  761. return 0;
  762. }
  763. int NetOptimize::fuse_deconvolution_add()
  764. {
  765. const size_t layer_count = layers.size();
  766. for (size_t i = 0; i < layer_count; i++)
  767. {
  768. if (layers[i]->type != "Deconvolution")
  769. continue;
  770. // Deconvolution - BinaryOp
  771. int top_blob_index = layers[i]->tops[0];
  772. size_t j = i + 1;
  773. for (; j < layer_count; j++)
  774. {
  775. if (layers[j]->type != "BinaryOp")
  776. continue;
  777. if (layers[j]->bottoms.size() != 2)
  778. continue;
  779. if (layers[j]->bottoms[0] == top_blob_index)
  780. break;
  781. }
  782. if (j == layer_count)
  783. continue;
  784. // fuse Deconvolution - BinaryOp to Deconvolution
  785. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  786. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  787. if (binaryop->op_type != 0 || binaryop->with_scalar)
  788. continue;
  789. // MemoryData - ..... - BinaryOp
  790. size_t k = 0;
  791. for (; k < j; k++)
  792. {
  793. if (layers[k]->type != "MemoryData")
  794. continue;
  795. if (layers[k]->tops[0] == binaryop->bottoms[1])
  796. break;
  797. }
  798. if (k == j)
  799. continue;
  800. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  801. int channels = deconvolution->num_output;
  802. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  803. {
  804. // not bias-like broadcasting type
  805. continue;
  806. }
  807. fprintf(stderr, "fuse_deconvolution_add %s %s\n", deconvolution->name.c_str(), binaryop->name.c_str());
  808. {
  809. if (deconvolution->bias_term == 0)
  810. {
  811. // init bias
  812. deconvolution->bias_term = 1;
  813. deconvolution->bias_data = memorydata->data;
  814. }
  815. else
  816. {
  817. float* bias = deconvolution->bias_data;
  818. for (int i = 0; i < channels; i++)
  819. {
  820. bias[i] = bias[i] + memorydata->data[i];
  821. }
  822. }
  823. }
  824. int top_blob_index_final = binaryop->tops[0];
  825. deconvolution->tops[0] = top_blob_index_final;
  826. blobs[top_blob_index_final].producer = i;
  827. binaryop->type = "ncnnfused";
  828. }
  829. return 0;
  830. }
  831. int NetOptimize::fuse_deconvolutiondepthwise_batchnorm()
  832. {
  833. const size_t layer_count = layers.size();
  834. for (size_t i = 0; i < layer_count; i++)
  835. {
  836. if (layers[i]->type != "DeconvolutionDepthWise")
  837. continue;
  838. // DeconvolutionDepthWise - BatchNorm
  839. int top_blob_index = layers[i]->tops[0];
  840. size_t j = i + 1;
  841. for (; j < layer_count; j++)
  842. {
  843. if (layers[j]->type != "BatchNorm")
  844. continue;
  845. if (layers[j]->bottoms.size() != 1)
  846. continue;
  847. if (layers[j]->bottoms[0] == top_blob_index)
  848. break;
  849. }
  850. if (j == layer_count)
  851. continue;
  852. // fuse DeconvolutionDepthWise - BatchNorm to DeconvolutionDepthWise
  853. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  854. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  855. fprintf(stderr, "fuse_deconvolutiondepthwise_batchnorm %s %s\n", deconvolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  856. {
  857. int channels = batchnorm->channels;
  858. float eps = batchnorm->eps;
  859. // a = bias - slope * mean / sqrt(var + eps)
  860. // b = slope / sqrt(var + eps)
  861. // value = value * b + a
  862. std::vector<float> a(channels);
  863. std::vector<float> b(channels);
  864. for (int i = 0; i < channels; i++)
  865. {
  866. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  867. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  868. b[i] = batchnorm->slope_data[i] / sqrt_var;
  869. }
  870. if (deconvolutiondepthwise->bias_term == 0)
  871. {
  872. // init bias as zero
  873. deconvolutiondepthwise->bias_term = 1;
  874. deconvolutiondepthwise->bias_data = ncnn::Mat(channels);
  875. deconvolutiondepthwise->bias_data.fill(0.f);
  876. }
  877. const int weight_per_outch = deconvolutiondepthwise->weight_data_size / channels;
  878. float* weight = deconvolutiondepthwise->weight_data;
  879. float* bias = deconvolutiondepthwise->bias_data;
  880. for (int i = 0; i < channels; i++)
  881. {
  882. float* conv_weight_outch = weight + weight_per_outch * i;
  883. for (int j = 0; j < weight_per_outch; j++)
  884. {
  885. conv_weight_outch[j] *= b[i];
  886. }
  887. bias[i] = bias[i] * b[i] + a[i];
  888. }
  889. }
  890. int top_blob_index_final = batchnorm->tops[0];
  891. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  892. blobs[top_blob_index_final].producer = i;
  893. batchnorm->type = "ncnnfused";
  894. }
  895. return 0;
  896. }
  897. int NetOptimize::fuse_innerproduct_batchnorm()
  898. {
  899. const size_t layer_count = layers.size();
  900. for (size_t i = 0; i < layer_count; i++)
  901. {
  902. if (layers[i]->type != "InnerProduct")
  903. continue;
  904. // InnerProduct - BatchNorm
  905. int top_blob_index = layers[i]->tops[0];
  906. size_t j = i + 1;
  907. for (; j < layer_count; j++)
  908. {
  909. if (layers[j]->type != "BatchNorm")
  910. continue;
  911. if (layers[j]->bottoms.size() != 1)
  912. continue;
  913. if (layers[j]->bottoms[0] == top_blob_index)
  914. break;
  915. }
  916. if (j == layer_count)
  917. continue;
  918. // fuse InnerProduct - BatchNorm to InnerProduct
  919. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  920. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  921. fprintf(stderr, "fuse_innerproduct_batchnorm %s %s\n", innerproduct->name.c_str(), batchnorm->name.c_str());
  922. {
  923. int channels = batchnorm->channels;
  924. float eps = batchnorm->eps;
  925. // a = bias - slope * mean / sqrt(var + eps)
  926. // b = slope / sqrt(var + eps)
  927. // value = value * b + a
  928. std::vector<float> a(channels);
  929. std::vector<float> b(channels);
  930. for (int i = 0; i < channels; i++)
  931. {
  932. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  933. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  934. b[i] = batchnorm->slope_data[i] / sqrt_var;
  935. }
  936. if (innerproduct->bias_term == 0)
  937. {
  938. // init bias as zero
  939. innerproduct->bias_term = 1;
  940. innerproduct->bias_data = ncnn::Mat(channels);
  941. innerproduct->bias_data.fill(0.f);
  942. }
  943. const int weight_per_outch = innerproduct->weight_data_size / channels;
  944. float* weight = innerproduct->weight_data;
  945. float* bias = innerproduct->bias_data;
  946. for (int i = 0; i < channels; i++)
  947. {
  948. float* conv_weight_outch = weight + weight_per_outch * i;
  949. for (int j = 0; j < weight_per_outch; j++)
  950. {
  951. conv_weight_outch[j] *= b[i];
  952. }
  953. bias[i] = bias[i] * b[i] + a[i];
  954. }
  955. }
  956. int top_blob_index_final = batchnorm->tops[0];
  957. innerproduct->tops[0] = top_blob_index_final;
  958. blobs[top_blob_index_final].producer = i;
  959. batchnorm->type = "ncnnfused";
  960. }
  961. return 0;
  962. }
  963. int NetOptimize::fuse_innerproduct_add()
  964. {
  965. const size_t layer_count = layers.size();
  966. for (size_t i = 0; i < layer_count; i++)
  967. {
  968. if (layers[i]->type != "InnerProduct")
  969. continue;
  970. // InnerProduct - BinaryOp
  971. int top_blob_index = layers[i]->tops[0];
  972. size_t j = i + 1;
  973. for (; j < layer_count; j++)
  974. {
  975. if (layers[j]->type != "BinaryOp")
  976. continue;
  977. if (layers[j]->bottoms.size() != 2)
  978. continue;
  979. if (layers[j]->bottoms[0] == top_blob_index)
  980. break;
  981. }
  982. if (j == layer_count)
  983. continue;
  984. // fuse InnerProduct - BinaryOp to InnerProduct
  985. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  986. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  987. if (binaryop->op_type != 0 || binaryop->with_scalar)
  988. continue;
  989. // MemoryData - ..... - BinaryOp
  990. size_t k = 0;
  991. for (; k < j; k++)
  992. {
  993. if (layers[k]->type != "MemoryData")
  994. continue;
  995. if (layers[k]->tops[0] == binaryop->bottoms[1])
  996. break;
  997. }
  998. if (k == j)
  999. continue;
  1000. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[k];
  1001. int channels = innerproduct->num_output;
  1002. if (memorydata->w != channels || memorydata->h != 0 || memorydata->c != 0)
  1003. {
  1004. // not bias-like broadcasting type
  1005. continue;
  1006. }
  1007. fprintf(stderr, "fuse_innerproduct_add %s %s\n", innerproduct->name.c_str(), binaryop->name.c_str());
  1008. {
  1009. if (innerproduct->bias_term == 0)
  1010. {
  1011. // init bias
  1012. innerproduct->bias_term = 1;
  1013. innerproduct->bias_data = memorydata->data;
  1014. }
  1015. else
  1016. {
  1017. float* bias = innerproduct->bias_data;
  1018. for (int i = 0; i < channels; i++)
  1019. {
  1020. bias[i] = bias[i] + memorydata->data[i];
  1021. }
  1022. }
  1023. }
  1024. int top_blob_index_final = binaryop->tops[0];
  1025. innerproduct->tops[0] = top_blob_index_final;
  1026. blobs[top_blob_index_final].producer = i;
  1027. binaryop->type = "ncnnfused";
  1028. }
  1029. return 0;
  1030. }
  1031. int NetOptimize::fuse_innerproduct_dropout()
  1032. {
  1033. const size_t layer_count = layers.size();
  1034. for (size_t i = 0; i < layer_count; i++)
  1035. {
  1036. if (layers[i]->type != "InnerProduct")
  1037. continue;
  1038. // InnerProduct - Dropout
  1039. int top_blob_index = layers[i]->tops[0];
  1040. size_t j = i + 1;
  1041. for (; j < layer_count; j++)
  1042. {
  1043. if (layers[j]->type != "Dropout")
  1044. continue;
  1045. if (layers[j]->bottoms.size() != 1)
  1046. continue;
  1047. if (layers[j]->bottoms[0] == top_blob_index)
  1048. break;
  1049. }
  1050. if (j == layer_count)
  1051. continue;
  1052. // fuse InnerProduct - Dropout to InnerProduct
  1053. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1054. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[j];
  1055. fprintf(stderr, "fuse_innerproduct_dropout %s %s\n", innerproduct->name.c_str(), dropout->name.c_str());
  1056. float scale = dropout->scale;
  1057. if (scale != 1.f)
  1058. {
  1059. const int num_output = innerproduct->num_output;
  1060. const int weight_per_outch = innerproduct->weight_data_size / num_output;
  1061. float* weight = innerproduct->weight_data;
  1062. for (int i = 0; i < num_output; i++)
  1063. {
  1064. float* conv_weight_outch = weight + weight_per_outch * i;
  1065. for (int j = 0; j < weight_per_outch; j++)
  1066. {
  1067. conv_weight_outch[j] *= scale;
  1068. }
  1069. }
  1070. if (innerproduct->bias_term)
  1071. {
  1072. float* bias = innerproduct->bias_data;
  1073. for (int i = 0; i < num_output; i++)
  1074. {
  1075. bias[i] *= scale;
  1076. }
  1077. }
  1078. }
  1079. int top_blob_index_final = dropout->tops[0];
  1080. innerproduct->tops[0] = top_blob_index_final;
  1081. blobs[top_blob_index_final].producer = i;
  1082. dropout->type = "ncnnfused";
  1083. }
  1084. return 0;
  1085. }
  1086. int NetOptimize::fuse_convolution_activation()
  1087. {
  1088. const size_t layer_count = layers.size();
  1089. for (size_t i = 0; i < layer_count; i++)
  1090. {
  1091. if (layers[i]->type != "Convolution")
  1092. continue;
  1093. // Convolution - Activation
  1094. int top_blob_index = layers[i]->tops[0];
  1095. size_t j = i + 1;
  1096. for (; j < layer_count; j++)
  1097. {
  1098. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid" && layers[j]->type != "Mish")
  1099. continue;
  1100. if (layers[j]->bottoms.size() != 1)
  1101. continue;
  1102. if (layers[j]->bottoms[0] == top_blob_index)
  1103. break;
  1104. }
  1105. if (j == layer_count)
  1106. continue;
  1107. // fuse Convolution - Activation to Convolution
  1108. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  1109. ncnn::Layer* activation = layers[j];
  1110. fprintf(stderr, "fuse_convolution_activation %s %s\n", convolution->name.c_str(), activation->name.c_str());
  1111. if (activation->type == "ReLU")
  1112. {
  1113. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1114. if (relu->slope == 0.f)
  1115. {
  1116. convolution->activation_type = 1;
  1117. }
  1118. else
  1119. {
  1120. convolution->activation_type = 2;
  1121. convolution->activation_params = ncnn::Mat(1);
  1122. convolution->activation_params[0] = relu->slope;
  1123. }
  1124. }
  1125. else if (activation->type == "Clip")
  1126. {
  1127. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1128. convolution->activation_type = 3;
  1129. convolution->activation_params = ncnn::Mat(2);
  1130. convolution->activation_params[0] = clip->min;
  1131. convolution->activation_params[1] = clip->max;
  1132. }
  1133. else if (activation->type == "Sigmoid")
  1134. {
  1135. convolution->activation_type = 4;
  1136. }
  1137. else if (activation->type == "Mish")
  1138. {
  1139. convolution->activation_type = 5;
  1140. }
  1141. int top_blob_index_final = activation->tops[0];
  1142. convolution->tops[0] = top_blob_index_final;
  1143. blobs[top_blob_index_final].producer = i;
  1144. activation->type = "ncnnfused";
  1145. }
  1146. return 0;
  1147. }
  1148. int NetOptimize::fuse_convolutiondepthwise_activation()
  1149. {
  1150. const size_t layer_count = layers.size();
  1151. for (size_t i = 0; i < layer_count; i++)
  1152. {
  1153. if (layers[i]->type != "ConvolutionDepthWise")
  1154. continue;
  1155. // ConvolutionDepthWise - Activation
  1156. int top_blob_index = layers[i]->tops[0];
  1157. size_t j = i + 1;
  1158. for (; j < layer_count; j++)
  1159. {
  1160. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid" && layers[j]->type != "Mish")
  1161. continue;
  1162. if (layers[j]->bottoms.size() != 1)
  1163. continue;
  1164. if (layers[j]->bottoms[0] == top_blob_index)
  1165. break;
  1166. }
  1167. if (j == layer_count)
  1168. continue;
  1169. // fuse ConvolutionDepthWise - Activation to ConvolutionDepthWise
  1170. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  1171. ncnn::Layer* activation = layers[j];
  1172. fprintf(stderr, "fuse_convolutiondepthwise_activation %s %s\n", convolutiondepthwise->name.c_str(), activation->name.c_str());
  1173. if (activation->type == "ReLU")
  1174. {
  1175. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1176. if (relu->slope == 0.f)
  1177. {
  1178. convolutiondepthwise->activation_type = 1;
  1179. }
  1180. else
  1181. {
  1182. convolutiondepthwise->activation_type = 2;
  1183. convolutiondepthwise->activation_params = ncnn::Mat(1);
  1184. convolutiondepthwise->activation_params[0] = relu->slope;
  1185. }
  1186. }
  1187. else if (activation->type == "Clip")
  1188. {
  1189. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1190. convolutiondepthwise->activation_type = 3;
  1191. convolutiondepthwise->activation_params = ncnn::Mat(2);
  1192. convolutiondepthwise->activation_params[0] = clip->min;
  1193. convolutiondepthwise->activation_params[1] = clip->max;
  1194. }
  1195. else if (activation->type == "Sigmoid")
  1196. {
  1197. convolutiondepthwise->activation_type = 4;
  1198. }
  1199. else if (activation->type == "Mish")
  1200. {
  1201. convolutiondepthwise->activation_type = 5;
  1202. }
  1203. int top_blob_index_final = activation->tops[0];
  1204. convolutiondepthwise->tops[0] = top_blob_index_final;
  1205. blobs[top_blob_index_final].producer = i;
  1206. activation->type = "ncnnfused";
  1207. }
  1208. return 0;
  1209. }
  1210. int NetOptimize::fuse_deconvolution_activation()
  1211. {
  1212. const size_t layer_count = layers.size();
  1213. for (size_t i = 0; i < layer_count; i++)
  1214. {
  1215. if (layers[i]->type != "Deconvolution")
  1216. continue;
  1217. // Deconvolution - Activation
  1218. int top_blob_index = layers[i]->tops[0];
  1219. size_t j = i + 1;
  1220. for (; j < layer_count; j++)
  1221. {
  1222. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1223. continue;
  1224. if (layers[j]->bottoms.size() != 1)
  1225. continue;
  1226. if (layers[j]->bottoms[0] == top_blob_index)
  1227. break;
  1228. }
  1229. if (j == layer_count)
  1230. continue;
  1231. // fuse Deconvolution - Activation to Deconvolution
  1232. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  1233. ncnn::Layer* activation = layers[j];
  1234. fprintf(stderr, "fuse_deconvolution_activation %s %s\n", deconvolution->name.c_str(), activation->name.c_str());
  1235. if (activation->type == "ReLU")
  1236. {
  1237. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1238. if (relu->slope == 0.f)
  1239. {
  1240. deconvolution->activation_type = 1;
  1241. }
  1242. else
  1243. {
  1244. deconvolution->activation_type = 2;
  1245. deconvolution->activation_params = ncnn::Mat(1);
  1246. deconvolution->activation_params[0] = relu->slope;
  1247. }
  1248. }
  1249. else if (activation->type == "Clip")
  1250. {
  1251. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1252. deconvolution->activation_type = 3;
  1253. deconvolution->activation_params = ncnn::Mat(2);
  1254. deconvolution->activation_params[0] = clip->min;
  1255. deconvolution->activation_params[1] = clip->max;
  1256. }
  1257. else if (activation->type == "Sigmoid")
  1258. {
  1259. deconvolution->activation_type = 4;
  1260. }
  1261. int top_blob_index_final = activation->tops[0];
  1262. deconvolution->tops[0] = top_blob_index_final;
  1263. blobs[top_blob_index_final].producer = i;
  1264. activation->type = "ncnnfused";
  1265. }
  1266. return 0;
  1267. }
  1268. int NetOptimize::fuse_deconvolutiondepthwise_activation()
  1269. {
  1270. const size_t layer_count = layers.size();
  1271. for (size_t i = 0; i < layer_count; i++)
  1272. {
  1273. if (layers[i]->type != "DeconvolutionDepthWise")
  1274. continue;
  1275. // DeconvolutionDepthWise - Activation
  1276. int top_blob_index = layers[i]->tops[0];
  1277. size_t j = i + 1;
  1278. for (; j < layer_count; j++)
  1279. {
  1280. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1281. continue;
  1282. if (layers[j]->bottoms.size() != 1)
  1283. continue;
  1284. if (layers[j]->bottoms[0] == top_blob_index)
  1285. break;
  1286. }
  1287. if (j == layer_count)
  1288. continue;
  1289. // fuse DeconvolutionDepthWise - Activation to DeconvolutionDepthWise
  1290. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  1291. ncnn::Layer* activation = layers[j];
  1292. fprintf(stderr, "fuse_deconvolutiondepthwise_activation %s %s\n", deconvolutiondepthwise->name.c_str(), activation->name.c_str());
  1293. if (activation->type == "ReLU")
  1294. {
  1295. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1296. if (relu->slope == 0.f)
  1297. {
  1298. deconvolutiondepthwise->activation_type = 1;
  1299. }
  1300. else
  1301. {
  1302. deconvolutiondepthwise->activation_type = 2;
  1303. deconvolutiondepthwise->activation_params = ncnn::Mat(1);
  1304. deconvolutiondepthwise->activation_params[0] = relu->slope;
  1305. }
  1306. }
  1307. else if (activation->type == "Clip")
  1308. {
  1309. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1310. deconvolutiondepthwise->activation_type = 3;
  1311. deconvolutiondepthwise->activation_params = ncnn::Mat(2);
  1312. deconvolutiondepthwise->activation_params[0] = clip->min;
  1313. deconvolutiondepthwise->activation_params[1] = clip->max;
  1314. }
  1315. else if (activation->type == "Sigmoid")
  1316. {
  1317. deconvolutiondepthwise->activation_type = 4;
  1318. }
  1319. int top_blob_index_final = activation->tops[0];
  1320. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  1321. blobs[top_blob_index_final].producer = i;
  1322. activation->type = "ncnnfused";
  1323. }
  1324. return 0;
  1325. }
  1326. int NetOptimize::fuse_innerproduct_activation()
  1327. {
  1328. const size_t layer_count = layers.size();
  1329. for (size_t i = 0; i < layer_count; i++)
  1330. {
  1331. if (layers[i]->type != "InnerProduct")
  1332. continue;
  1333. // InnerProduct - Activation
  1334. int top_blob_index = layers[i]->tops[0];
  1335. size_t j = i + 1;
  1336. for (; j < layer_count; j++)
  1337. {
  1338. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  1339. continue;
  1340. if (layers[j]->bottoms.size() != 1)
  1341. continue;
  1342. if (layers[j]->bottoms[0] == top_blob_index)
  1343. break;
  1344. }
  1345. if (j == layer_count)
  1346. continue;
  1347. // fuse InnerProduct - Activation to InnerProduct
  1348. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1349. ncnn::Layer* activation = layers[j];
  1350. fprintf(stderr, "fuse_innerproduct_activation %s %s\n", innerproduct->name.c_str(), activation->name.c_str());
  1351. if (activation->type == "ReLU")
  1352. {
  1353. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  1354. if (relu->slope == 0.f)
  1355. {
  1356. innerproduct->activation_type = 1;
  1357. }
  1358. else
  1359. {
  1360. innerproduct->activation_type = 2;
  1361. innerproduct->activation_params = ncnn::Mat(1);
  1362. innerproduct->activation_params[0] = relu->slope;
  1363. }
  1364. }
  1365. else if (activation->type == "Clip")
  1366. {
  1367. ncnn::Clip* clip = (ncnn::Clip*)activation;
  1368. innerproduct->activation_type = 3;
  1369. innerproduct->activation_params = ncnn::Mat(2);
  1370. innerproduct->activation_params[0] = clip->min;
  1371. innerproduct->activation_params[1] = clip->max;
  1372. }
  1373. else if (activation->type == "Sigmoid")
  1374. {
  1375. innerproduct->activation_type = 4;
  1376. }
  1377. int top_blob_index_final = activation->tops[0];
  1378. innerproduct->tops[0] = top_blob_index_final;
  1379. blobs[top_blob_index_final].producer = i;
  1380. activation->type = "ncnnfused";
  1381. }
  1382. return 0;
  1383. }
  1384. int NetOptimize::fuse_memorydata_binaryop()
  1385. {
  1386. const size_t layer_count = layers.size();
  1387. for (size_t i = 0; i < layer_count; i++)
  1388. {
  1389. if (layers[i]->type != "MemoryData")
  1390. continue;
  1391. // MemoryData - BinaryOp
  1392. int top_blob_index = layers[i]->tops[0];
  1393. size_t j = i + 1;
  1394. for (; j < layer_count; j++)
  1395. {
  1396. if (layers[j]->type != "BinaryOp")
  1397. continue;
  1398. if (layers[j]->bottoms.size() != 2)
  1399. continue;
  1400. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1401. break;
  1402. }
  1403. if (j == layer_count)
  1404. continue;
  1405. // fuse MemoryData - BinaryOp to BinaryOp
  1406. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[i];
  1407. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1408. if (memorydata->w != 1 || memorydata->h != 0 || memorydata->c != 0)
  1409. {
  1410. // not a scalar
  1411. continue;
  1412. }
  1413. int memorydata_index = 1;
  1414. if (binaryop->bottoms[0] == top_blob_index)
  1415. {
  1416. int op_type = binaryop->op_type;
  1417. if (op_type == ncnn::BinaryOp::Operation_ADD
  1418. || op_type == ncnn::BinaryOp::Operation_MUL
  1419. || op_type == ncnn::BinaryOp::Operation_MAX
  1420. || op_type == ncnn::BinaryOp::Operation_MIN)
  1421. {
  1422. memorydata_index = 0;
  1423. }
  1424. else if (op_type == ncnn::BinaryOp::Operation_SUB)
  1425. {
  1426. binaryop->op_type = ncnn::BinaryOp::Operation_RSUB;
  1427. memorydata_index = 0;
  1428. }
  1429. else if (op_type == ncnn::BinaryOp::Operation_DIV)
  1430. {
  1431. binaryop->op_type = ncnn::BinaryOp::Operation_RDIV;
  1432. memorydata_index = 0;
  1433. }
  1434. else
  1435. {
  1436. // non interchangeable binaryop
  1437. continue;
  1438. }
  1439. }
  1440. float scalar = memorydata->data[0];
  1441. binaryop->with_scalar = 1;
  1442. binaryop->b = scalar;
  1443. fprintf(stderr, "fuse_memorydata_binaryop %s %s\n", memorydata->name.c_str(), binaryop->name.c_str());
  1444. binaryop->bottoms.erase(binaryop->bottoms.begin() + memorydata_index);
  1445. memorydata->type = "ncnnfused";
  1446. }
  1447. for (size_t i = 0; i < layer_count; i++)
  1448. {
  1449. if (layers[i]->type != "MemoryData")
  1450. continue;
  1451. // MemoryData - Split - BinaryOp
  1452. int top_blob_index = layers[i]->tops[0];
  1453. size_t j0 = i + 1;
  1454. for (; j0 < layer_count; j0++)
  1455. {
  1456. if (layers[j0]->type != "Split")
  1457. continue;
  1458. if (layers[j0]->bottoms.size() != 1)
  1459. continue;
  1460. if (layers[j0]->bottoms[0] == top_blob_index)
  1461. break;
  1462. }
  1463. if (j0 == layer_count)
  1464. continue;
  1465. int split_top_blob_index = -1;
  1466. size_t j1 = j0 + 1;
  1467. for (; j1 < layer_count; j1++)
  1468. {
  1469. if (layers[j1]->type != "BinaryOp")
  1470. continue;
  1471. if (layers[j1]->bottoms.size() != 2)
  1472. continue;
  1473. for (int k = 0; k < (int)layers[j0]->tops.size(); k++)
  1474. {
  1475. if (layers[j1]->bottoms[0] == layers[j0]->tops[k] || layers[j1]->bottoms[1] == layers[j0]->tops[k])
  1476. {
  1477. split_top_blob_index = k;
  1478. break;
  1479. }
  1480. }
  1481. if (split_top_blob_index != -1)
  1482. break;
  1483. }
  1484. if (j1 == layer_count)
  1485. continue;
  1486. // fuse MemoryData - Split - BinaryOp to BinaryOp
  1487. ncnn::MemoryData* memorydata = (ncnn::MemoryData*)layers[i];
  1488. ncnn::Split* split = (ncnn::Split*)layers[j0];
  1489. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j1];
  1490. if (memorydata->w != 1 || memorydata->h != 0 || memorydata->c != 0)
  1491. {
  1492. // not a scalar
  1493. continue;
  1494. }
  1495. int memorydata_index = 1;
  1496. if (binaryop->bottoms[0] == split->tops[split_top_blob_index])
  1497. {
  1498. int op_type = binaryop->op_type;
  1499. if (op_type == ncnn::BinaryOp::Operation_ADD
  1500. || op_type == ncnn::BinaryOp::Operation_MUL
  1501. || op_type == ncnn::BinaryOp::Operation_MAX
  1502. || op_type == ncnn::BinaryOp::Operation_MIN)
  1503. {
  1504. memorydata_index = 0;
  1505. }
  1506. else if (op_type == ncnn::BinaryOp::Operation_SUB)
  1507. {
  1508. binaryop->op_type = ncnn::BinaryOp::Operation_RSUB;
  1509. memorydata_index = 0;
  1510. }
  1511. else if (op_type == ncnn::BinaryOp::Operation_DIV)
  1512. {
  1513. binaryop->op_type = ncnn::BinaryOp::Operation_RDIV;
  1514. memorydata_index = 0;
  1515. }
  1516. else
  1517. {
  1518. // non interchangeable binaryop
  1519. continue;
  1520. }
  1521. }
  1522. float scalar = memorydata->data[0];
  1523. binaryop->with_scalar = 1;
  1524. binaryop->b = scalar;
  1525. fprintf(stderr, "fuse_memorydata_binaryop %s %s\n", memorydata->name.c_str(), binaryop->name.c_str());
  1526. binaryop->bottoms.erase(binaryop->bottoms.begin() + memorydata_index);
  1527. split->tops.erase(split->tops.begin() + split_top_blob_index);
  1528. if (split->tops.empty())
  1529. {
  1530. split->type = "ncnnfused";
  1531. memorydata->type = "ncnnfused";
  1532. }
  1533. i--;
  1534. }
  1535. return 0;
  1536. }
  1537. int NetOptimize::fuse_binaryop_eltwise()
  1538. {
  1539. const size_t layer_count = layers.size();
  1540. for (size_t i = 0; i < layer_count; i++)
  1541. {
  1542. if (layers[i]->type != "BinaryOp")
  1543. continue;
  1544. if (layers[i]->bottoms.size() != 2)
  1545. continue;
  1546. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[i];
  1547. if (binaryop->op_type != ncnn::BinaryOp::Operation_ADD)
  1548. continue;
  1549. if (binaryop->with_scalar)
  1550. continue;
  1551. // BinaryOp - BinaryOp - BinaryOp
  1552. int bottom_blob_index_0 = binaryop->bottoms[0];
  1553. int bottom_blob_index_1 = binaryop->bottoms[1];
  1554. size_t j0 = 0;
  1555. for (; j0 < i; j0++)
  1556. {
  1557. if (layers[j0]->type != "BinaryOp")
  1558. continue;
  1559. if (layers[j0]->bottoms.size() != 1)
  1560. continue;
  1561. if (((ncnn::BinaryOp*)layers[j0])->op_type != ncnn::BinaryOp::Operation_MUL)
  1562. continue;
  1563. if (layers[j0]->tops[0] == bottom_blob_index_0)
  1564. break;
  1565. }
  1566. size_t j1 = 0;
  1567. for (; j1 < i; j1++)
  1568. {
  1569. if (layers[j1]->type != "BinaryOp")
  1570. continue;
  1571. if (layers[j1]->bottoms.size() != 1)
  1572. continue;
  1573. if (((ncnn::BinaryOp*)layers[j1])->op_type != ncnn::BinaryOp::Operation_MUL)
  1574. continue;
  1575. if (layers[j1]->tops[0] == bottom_blob_index_1)
  1576. break;
  1577. }
  1578. if (j0 == i && j1 == i)
  1579. continue;
  1580. ncnn::BinaryOp* binaryop0 = (ncnn::BinaryOp*)layers[j0];
  1581. ncnn::BinaryOp* binaryop1 = (ncnn::BinaryOp*)layers[j1];
  1582. fprintf(stderr, "fuse_binaryop_eltwise %s %s %s\n", binaryop0->name.c_str(), binaryop1->name.c_str(), binaryop->name.c_str());
  1583. ncnn::Eltwise* eltwise = (ncnn::Eltwise*)ncnn::create_layer("Eltwise");
  1584. eltwise->type = "Eltwise";
  1585. eltwise->name = binaryop->name;
  1586. eltwise->bottoms = binaryop->bottoms;
  1587. eltwise->tops = binaryop->tops;
  1588. ncnn::ParamDict pd;
  1589. eltwise->load_param(pd);
  1590. eltwise->op_type = ncnn::Eltwise::Operation_SUM;
  1591. eltwise->coeffs = ncnn::Mat(2);
  1592. if (j0 != i && j1 != i)
  1593. {
  1594. // fuse BinaryOp - BinaryOp - BinaryOp to Eltwise
  1595. eltwise->coeffs[0] = binaryop0->b;
  1596. eltwise->coeffs[1] = binaryop1->b;
  1597. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1598. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1599. binaryop0->type = "ncnnfused";
  1600. binaryop1->type = "ncnnfused";
  1601. }
  1602. if (j0 != i && j1 == i)
  1603. {
  1604. // fuse BinaryOp - X - BinaryOp to Eltwise
  1605. eltwise->coeffs[0] = binaryop0->b;
  1606. eltwise->coeffs[1] = 1.f;
  1607. eltwise->bottoms[0] = binaryop0->bottoms[0];
  1608. binaryop0->type = "ncnnfused";
  1609. }
  1610. if (j0 == i && j1 != i)
  1611. {
  1612. // fuse X - BinaryOp - BinaryOp to Eltwise
  1613. eltwise->coeffs[0] = 1.f;
  1614. eltwise->coeffs[1] = binaryop1->b;
  1615. eltwise->bottoms[1] = binaryop1->bottoms[0];
  1616. binaryop1->type = "ncnnfused";
  1617. }
  1618. layers[i] = eltwise;
  1619. delete binaryop;
  1620. }
  1621. return 0;
  1622. }
  1623. int NetOptimize::eliminate_dropout()
  1624. {
  1625. const size_t layer_count = layers.size();
  1626. for (size_t i = 0; i < layer_count; i++)
  1627. {
  1628. if (layers[i]->type != "Dropout")
  1629. continue;
  1630. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[i];
  1631. if (dropout->scale != 1.f)
  1632. continue;
  1633. // Any - Dropout
  1634. int bottom_blob_index = layers[i]->bottoms[0];
  1635. int j = i - 1;
  1636. for (; j >= 0; j--)
  1637. {
  1638. if (layers[j]->type == "ncnnfused")
  1639. continue;
  1640. if (layers[j]->tops.size() != 1)
  1641. continue;
  1642. if (layers[j]->tops[0] == bottom_blob_index)
  1643. break;
  1644. }
  1645. if (j == -1)
  1646. continue;
  1647. ncnn::Layer* any = layers[j];
  1648. fprintf(stderr, "eliminate_dropout %s %s\n", any->name.c_str(), dropout->name.c_str());
  1649. int top_blob_index_final = dropout->tops[0];
  1650. any->tops[0] = top_blob_index_final;
  1651. blobs[top_blob_index_final].producer = j;
  1652. dropout->type = "ncnnfused";
  1653. }
  1654. return 0;
  1655. }
  1656. int NetOptimize::eliminate_pooling1x1()
  1657. {
  1658. const size_t layer_count = layers.size();
  1659. for (size_t i = 0; i < layer_count; i++)
  1660. {
  1661. if (layers[i]->type != "Pooling")
  1662. continue;
  1663. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1664. if (pooling->pad_left != 0 || pooling->pad_right != 0 || pooling->pad_top != 0 || pooling->pad_bottom != 0)
  1665. continue;
  1666. if (pooling->kernel_w != 1 || pooling->kernel_h != 1 || pooling->stride_w != 1 || pooling->stride_h != 1)
  1667. continue;
  1668. if (pooling->global_pooling != 0)
  1669. continue;
  1670. // Any - Pooling
  1671. int bottom_blob_index = layers[i]->bottoms[0];
  1672. int top_i = -1;
  1673. int j = i - 1;
  1674. for (; j >= 0; j--)
  1675. {
  1676. if (layers[j]->type == "ncnnfused")
  1677. continue;
  1678. for (size_t k = 0; k < layers[j]->tops.size(); k++)
  1679. {
  1680. if (layers[j]->tops[k] == bottom_blob_index)
  1681. {
  1682. top_i = k;
  1683. break;
  1684. }
  1685. }
  1686. if (top_i != -1)
  1687. break;
  1688. }
  1689. if (j == -1)
  1690. continue;
  1691. ncnn::Layer* any = layers[j];
  1692. fprintf(stderr, "eliminate_pooling1x1 %s %s\n", any->name.c_str(), pooling->name.c_str());
  1693. int top_blob_index_final = pooling->tops[0];
  1694. any->tops[top_i] = top_blob_index_final;
  1695. blobs[top_blob_index_final].producer = j;
  1696. pooling->type = "ncnnfused";
  1697. }
  1698. return 0;
  1699. }
  1700. int NetOptimize::eliminate_noop()
  1701. {
  1702. const size_t layer_count = layers.size();
  1703. for (size_t i = 0; i < layer_count; i++)
  1704. {
  1705. if (layers[i]->type != "Noop")
  1706. continue;
  1707. ncnn::Layer* noop = layers[i];
  1708. if (noop->bottoms.empty())
  1709. {
  1710. // Noop
  1711. fprintf(stderr, "eliminate_noop %s\n", noop->name.c_str());
  1712. size_t top_blob_count = noop->tops.size();
  1713. for (size_t k = 0; k < top_blob_count; k++)
  1714. {
  1715. int top_blob_index_final = noop->tops[k];
  1716. blobs[top_blob_index_final].producer = -1;
  1717. }
  1718. noop->type = "ncnnfused";
  1719. continue;
  1720. }
  1721. // Any - Noop
  1722. int bottom_blob_index = layers[i]->bottoms[0];
  1723. int j = i - 1;
  1724. for (; j >= 0; j--)
  1725. {
  1726. if (layers[j]->type == "ncnnfused")
  1727. continue;
  1728. if (layers[j]->tops.size() != 1)
  1729. continue;
  1730. if (layers[j]->tops[0] == bottom_blob_index)
  1731. break;
  1732. }
  1733. if (j == -1)
  1734. continue;
  1735. ncnn::Layer* any = layers[j];
  1736. fprintf(stderr, "eliminate_noop %s %s\n", any->name.c_str(), noop->name.c_str());
  1737. size_t top_blob_count = std::min(noop->tops.size(), any->tops.size());
  1738. for (size_t k = 0; k < top_blob_count; k++)
  1739. {
  1740. int top_blob_index_final = noop->tops[k];
  1741. any->tops[k] = top_blob_index_final;
  1742. blobs[top_blob_index_final].producer = j;
  1743. }
  1744. noop->type = "ncnnfused";
  1745. }
  1746. return 0;
  1747. }
  1748. int NetOptimize::eliminate_orphaned_memorydata()
  1749. {
  1750. const size_t layer_count = layers.size();
  1751. for (size_t i = 0; i < layer_count; i++)
  1752. {
  1753. if (layers[i]->type != "MemoryData")
  1754. continue;
  1755. // MemoryData - X
  1756. int top_blob_index = layers[i]->tops[0];
  1757. size_t j = i + 1;
  1758. for (; j < layer_count; j++)
  1759. {
  1760. if (layers[j]->type == "ncnnfused")
  1761. continue;
  1762. bool orphaned = true;
  1763. for (size_t k = 0; k < layers[j]->bottoms.size(); k++)
  1764. {
  1765. if (layers[j]->bottoms[k] == top_blob_index)
  1766. {
  1767. orphaned = false;
  1768. break;
  1769. }
  1770. }
  1771. if (!orphaned)
  1772. break;
  1773. }
  1774. if (j < layer_count)
  1775. continue;
  1776. // assert orphaned == true
  1777. fprintf(stderr, "eliminate_orphaned_memorydata %s\n", layers[i]->name.c_str());
  1778. layers[i]->type = "ncnnfused";
  1779. }
  1780. return 0;
  1781. }
  1782. int NetOptimize::eliminate_reshape_after_global_pooling()
  1783. {
  1784. const size_t layer_count = layers.size();
  1785. for (size_t i = 0; i < layer_count; i++)
  1786. {
  1787. if (layers[i]->type != "Pooling")
  1788. continue;
  1789. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1790. if (pooling->global_pooling == 0)
  1791. continue;
  1792. // Pooling - Reshape
  1793. int top_blob_index = layers[i]->tops[0];
  1794. size_t j = i + 1;
  1795. for (; j < layer_count; j++)
  1796. {
  1797. if (layers[j]->type != "Reshape")
  1798. continue;
  1799. if (layers[j]->bottoms.size() != 1)
  1800. continue;
  1801. if (layers[j]->bottoms[0] == top_blob_index)
  1802. break;
  1803. }
  1804. if (j == layer_count)
  1805. continue;
  1806. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[j];
  1807. if (reshape->h != -233 || reshape->c != -233 || reshape->permute != 0)
  1808. continue;
  1809. fprintf(stderr, "eliminate_reshape_after_global_pooling %s %s\n", pooling->name.c_str(), reshape->name.c_str());
  1810. int top_blob_index_final = reshape->tops[0];
  1811. pooling->tops[0] = top_blob_index_final;
  1812. blobs[top_blob_index_final].producer = i;
  1813. reshape->type = "ncnnfused";
  1814. }
  1815. return 0;
  1816. }
  1817. int NetOptimize::eliminate_flatten_after_global_pooling()
  1818. {
  1819. const size_t layer_count = layers.size();
  1820. for (size_t i = 0; i < layer_count; i++)
  1821. {
  1822. if (layers[i]->type != "Pooling")
  1823. continue;
  1824. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1825. if (pooling->global_pooling == 0)
  1826. continue;
  1827. // Pooling - Flatten
  1828. int top_blob_index = layers[i]->tops[0];
  1829. size_t j = i + 1;
  1830. for (; j < layer_count; j++)
  1831. {
  1832. if (layers[j]->type != "Flatten")
  1833. continue;
  1834. if (layers[j]->bottoms.size() != 1)
  1835. continue;
  1836. if (layers[j]->bottoms[0] == top_blob_index)
  1837. break;
  1838. }
  1839. if (j == layer_count)
  1840. continue;
  1841. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1842. fprintf(stderr, "eliminate_flatten_after_global_pooling %s %s\n", pooling->name.c_str(), flatten->name.c_str());
  1843. int top_blob_index_final = flatten->tops[0];
  1844. pooling->tops[0] = top_blob_index_final;
  1845. blobs[top_blob_index_final].producer = i;
  1846. flatten->type = "ncnnfused";
  1847. }
  1848. return 0;
  1849. }
  1850. int NetOptimize::eliminate_flatten_after_innerproduct()
  1851. {
  1852. const size_t layer_count = layers.size();
  1853. for (size_t i = 0; i < layer_count; i++)
  1854. {
  1855. if (layers[i]->type != "InnerProduct")
  1856. continue;
  1857. // InnerProduct - Flatten
  1858. int top_blob_index = layers[i]->tops[0];
  1859. size_t j = i + 1;
  1860. for (; j < layer_count; j++)
  1861. {
  1862. if (layers[j]->type != "Flatten")
  1863. continue;
  1864. if (layers[j]->bottoms.size() != 1)
  1865. continue;
  1866. if (layers[j]->bottoms[0] == top_blob_index)
  1867. break;
  1868. }
  1869. if (j == layer_count)
  1870. continue;
  1871. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1872. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1873. fprintf(stderr, "eliminate_flatten_after_innerproduct %s %s\n", innerproduct->name.c_str(), flatten->name.c_str());
  1874. int top_blob_index_final = flatten->tops[0];
  1875. innerproduct->tops[0] = top_blob_index_final;
  1876. blobs[top_blob_index_final].producer = i;
  1877. flatten->type = "ncnnfused";
  1878. }
  1879. return 0;
  1880. }
  1881. int NetOptimize::eliminate_reshape_before_binaryop()
  1882. {
  1883. const size_t layer_count = layers.size();
  1884. for (size_t i = 0; i < layer_count; i++)
  1885. {
  1886. if (layers[i]->type != "Reshape")
  1887. continue;
  1888. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[i];
  1889. if (reshape->w != 1 || reshape->h != 1 || reshape->permute != 0)
  1890. continue;
  1891. // Reshape - BinaryOp
  1892. int top_blob_index = layers[i]->tops[0];
  1893. size_t j = i + 1;
  1894. for (; j < layer_count; j++)
  1895. {
  1896. if (layers[j]->type != "BinaryOp")
  1897. continue;
  1898. if (layers[j]->bottoms.size() != 2)
  1899. continue;
  1900. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1901. break;
  1902. }
  1903. if (j == layer_count)
  1904. continue;
  1905. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1906. fprintf(stderr, "eliminate_reshape_before_binaryop %s %s\n", reshape->name.c_str(), binaryop->name.c_str());
  1907. int bottom_blob_index_final = reshape->bottoms[0];
  1908. if (layers[j]->bottoms[0] == top_blob_index)
  1909. binaryop->bottoms[0] = bottom_blob_index_final;
  1910. if (layers[j]->bottoms[1] == top_blob_index)
  1911. binaryop->bottoms[1] = bottom_blob_index_final;
  1912. blobs[bottom_blob_index_final].consumers.erase(std::find(blobs[bottom_blob_index_final].consumers.begin(), blobs[bottom_blob_index_final].consumers.end(), i));
  1913. blobs[bottom_blob_index_final].consumers.push_back(j);
  1914. reshape->type = "ncnnfused";
  1915. }
  1916. return 0;
  1917. }
  1918. int NetOptimize::replace_reduction_with_global_pooling()
  1919. {
  1920. const size_t layer_count = layers.size();
  1921. for (size_t i = 0; i < layer_count; i++)
  1922. {
  1923. if (layers[i]->type != "Reduction")
  1924. continue;
  1925. ncnn::Reduction* reduction1 = (ncnn::Reduction*)layers[i];
  1926. if (reduction1->operation != 3 || reduction1->reduce_all != 0 || reduction1->coeff != 1.f)
  1927. continue;
  1928. if (reduction1->axes.w != 1)
  1929. continue;
  1930. const int* axes_ptr = reduction1->axes;
  1931. if (axes_ptr[0] != 2 && axes_ptr[0] != 3)
  1932. continue;
  1933. // Reduction(2/3) - Reduction(2)
  1934. int top_blob_index = layers[i]->tops[0];
  1935. size_t j = i + 1;
  1936. for (; j < layer_count; j++)
  1937. {
  1938. if (layers[j]->type != "Reduction")
  1939. continue;
  1940. if (layers[j]->bottoms.size() != 1)
  1941. continue;
  1942. if (layers[j]->bottoms[0] == top_blob_index)
  1943. break;
  1944. }
  1945. if (j == layer_count)
  1946. continue;
  1947. ncnn::Reduction* reduction2 = (ncnn::Reduction*)layers[j];
  1948. if (reduction2->operation != 3 || reduction2->reduce_all != 0 || reduction2->coeff != 1.f)
  1949. continue;
  1950. if (reduction2->axes.w != 1)
  1951. continue;
  1952. const int* axes2_ptr = reduction2->axes;
  1953. if (axes2_ptr[0] != 2)
  1954. continue;
  1955. fprintf(stderr, "replace_reduction_with_global_pooling %s %s\n", reduction1->name.c_str(), reduction2->name.c_str());
  1956. ncnn::Pooling* pooling = (ncnn::Pooling*)ncnn::create_layer("Pooling");
  1957. pooling->type = "Pooling";
  1958. pooling->name = reduction2->name;
  1959. pooling->bottoms = reduction2->bottoms;
  1960. pooling->tops = reduction2->tops;
  1961. ncnn::ParamDict pd;
  1962. pooling->load_param(pd);
  1963. pooling->pooling_type = 1;
  1964. pooling->global_pooling = 1;
  1965. layers[j] = pooling;
  1966. delete reduction2;
  1967. int bottom_blob_index_final = reduction1->bottoms[0];
  1968. pooling->bottoms[0] = bottom_blob_index_final;
  1969. blobs[bottom_blob_index_final].consumers.clear();
  1970. blobs[bottom_blob_index_final].consumers.push_back(j);
  1971. reduction1->type = "ncnnfused";
  1972. }
  1973. return 0;
  1974. }
  1975. int NetOptimize::replace_prelu_with_leaky_relu()
  1976. {
  1977. const size_t layer_count = layers.size();
  1978. for (size_t i = 0; i < layer_count; i++)
  1979. {
  1980. if (layers[i]->type != "PReLU")
  1981. continue;
  1982. ncnn::PReLU* prelu = (ncnn::PReLU*)layers[i];
  1983. if (prelu->num_slope != 1)
  1984. continue;
  1985. fprintf(stderr, "replace_prelu_with_leaky_relu %s\n", prelu->name.c_str());
  1986. ncnn::ReLU* relu = (ncnn::ReLU*)ncnn::create_layer("ReLU");
  1987. relu->type = "ReLU";
  1988. relu->name = prelu->name;
  1989. relu->bottoms = prelu->bottoms;
  1990. relu->tops = prelu->tops;
  1991. ncnn::ParamDict pd;
  1992. relu->load_param(pd);
  1993. relu->slope = prelu->slope_data[0];
  1994. layers[i] = relu;
  1995. delete prelu;
  1996. }
  1997. return 0;
  1998. }
  1999. int NetOptimize::replace_convolution_with_innerproduct_after_global_pooling()
  2000. {
  2001. const size_t layer_count = layers.size();
  2002. for (size_t i = 0; i < layer_count; i++)
  2003. {
  2004. if (layers[i]->type != "Pooling")
  2005. continue;
  2006. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  2007. if (pooling->global_pooling == 0)
  2008. continue;
  2009. // Pooling - Convolution
  2010. int top_blob_index = layers[i]->tops[0];
  2011. size_t j = i + 1;
  2012. for (; j < layer_count; j++)
  2013. {
  2014. if (layers[j]->type != "Convolution")
  2015. continue;
  2016. if (layers[j]->bottoms.size() != 1)
  2017. continue;
  2018. if (layers[j]->bottoms[0] == top_blob_index)
  2019. break;
  2020. }
  2021. if (j == layer_count)
  2022. continue;
  2023. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  2024. fprintf(stderr, "replace_convolution_with_innerproduct_after_global_pooling %s %s\n", pooling->name.c_str(), convolution->name.c_str());
  2025. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  2026. innerproduct->type = "InnerProduct";
  2027. innerproduct->name = convolution->name;
  2028. innerproduct->bottoms = convolution->bottoms;
  2029. innerproduct->tops = convolution->tops;
  2030. ncnn::ParamDict pd;
  2031. innerproduct->load_param(pd);
  2032. innerproduct->num_output = convolution->num_output;
  2033. innerproduct->bias_term = convolution->bias_term;
  2034. innerproduct->weight_data_size = convolution->weight_data_size;
  2035. innerproduct->int8_scale_term = convolution->int8_scale_term;
  2036. innerproduct->weight_data = convolution->weight_data;
  2037. innerproduct->bias_data = convolution->bias_data;
  2038. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  2039. innerproduct->bottom_blob_int8_scale = convolution->bottom_blob_int8_scale;
  2040. innerproduct->activation_type = convolution->activation_type;
  2041. innerproduct->activation_params = convolution->activation_params;
  2042. layers[j] = innerproduct;
  2043. delete convolution;
  2044. }
  2045. return 0;
  2046. }
  2047. int NetOptimize::replace_convolution_with_innerproduct_after_innerproduct()
  2048. {
  2049. const size_t layer_count = layers.size();
  2050. for (;;)
  2051. {
  2052. bool replaced = false;
  2053. for (size_t i = 0; i < layer_count; i++)
  2054. {
  2055. if (layers[i]->type != "InnerProduct")
  2056. continue;
  2057. // InnerProduct - Convolution
  2058. int top_blob_index = layers[i]->tops[0];
  2059. size_t j = i + 1;
  2060. for (; j < layer_count; j++)
  2061. {
  2062. if (layers[j]->type != "Convolution")
  2063. continue;
  2064. if (layers[j]->bottoms.size() != 1)
  2065. continue;
  2066. if (layers[j]->bottoms[0] == top_blob_index)
  2067. break;
  2068. }
  2069. if (j == layer_count)
  2070. continue;
  2071. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  2072. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  2073. fprintf(stderr, "replace_convolution_with_innerproduct_after_innerproduct %s %s\n", innerproduct->name.c_str(), convolution->name.c_str());
  2074. ncnn::InnerProduct* innerproduct2 = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  2075. innerproduct2->type = "InnerProduct";
  2076. innerproduct2->name = convolution->name;
  2077. innerproduct2->bottoms = convolution->bottoms;
  2078. innerproduct2->tops = convolution->tops;
  2079. ncnn::ParamDict pd;
  2080. innerproduct2->load_param(pd);
  2081. innerproduct2->num_output = convolution->num_output;
  2082. innerproduct2->bias_term = convolution->bias_term;
  2083. innerproduct2->weight_data_size = convolution->weight_data_size;
  2084. innerproduct->int8_scale_term = convolution->int8_scale_term;
  2085. innerproduct2->weight_data = convolution->weight_data;
  2086. innerproduct2->bias_data = convolution->bias_data;
  2087. innerproduct->weight_data_int8_scales = convolution->weight_data_int8_scales;
  2088. innerproduct->bottom_blob_int8_scale = convolution->bottom_blob_int8_scale;
  2089. innerproduct2->activation_type = convolution->activation_type;
  2090. innerproduct2->activation_params = convolution->activation_params;
  2091. layers[j] = innerproduct2;
  2092. delete convolution;
  2093. replaced = true;
  2094. }
  2095. if (!replaced)
  2096. break;
  2097. }
  2098. return 0;
  2099. }
  2100. int NetOptimize::shape_inference()
  2101. {
  2102. const size_t layer_count = layers.size();
  2103. const size_t blob_count = blobs.size();
  2104. ncnn::Extractor ex = create_extractor();
  2105. // prepare Input blobs
  2106. for (size_t i = 0; i < layer_count; i++)
  2107. {
  2108. const ncnn::Layer* layer = layers[i];
  2109. if (layer->type == "ncnnfused")
  2110. continue;
  2111. if (layer->type != "Input")
  2112. continue;
  2113. ncnn::Input* input = (ncnn::Input*)layer;
  2114. int w = input->w;
  2115. int h = input->h;
  2116. int c = input->c;
  2117. int dims = 0;
  2118. if (w == 0 && h == 0 && c == 0) dims = 0;
  2119. if (w != 0 && h == 0 && c == 0) dims = 1;
  2120. if (w != 0 && h != 0 && c == 0) dims = 2;
  2121. if (w != 0 && h != 0 && c != 0) dims = 3;
  2122. if (dims == 0)
  2123. {
  2124. fprintf(stderr, "Input layer %s without shape info, shape_inference aborted\n", layer->name.c_str());
  2125. return -1;
  2126. }
  2127. ncnn::Mat m;
  2128. if (dims == 1) m.create(w);
  2129. if (dims == 2) m.create(w, h);
  2130. if (dims == 3) m.create(w, h, c);
  2131. ex.input(layer->tops[0], m);
  2132. }
  2133. // prepare blobs with predefined shape
  2134. for (size_t i = 0; i < blob_count; i++)
  2135. {
  2136. const ncnn::Blob& blob = blobs[i];
  2137. int dims = blob.shape.dims;
  2138. int w = blob.shape.w;
  2139. int h = blob.shape.h;
  2140. int c = blob.shape.c;
  2141. if (dims == 0)
  2142. continue;
  2143. ncnn::Mat m;
  2144. if (dims == 1) m.create(w);
  2145. if (dims == 2) m.create(w, h);
  2146. if (dims == 3) m.create(w, h, c);
  2147. ex.input(int(i), m);
  2148. }
  2149. fprintf(stderr, "shape_inference\n");
  2150. // resolve all layer output blob shape
  2151. for (size_t i = 0; i < layer_count; i++)
  2152. {
  2153. const ncnn::Layer* layer = layers[i];
  2154. if (layer->type == "ncnnfused")
  2155. continue;
  2156. for (size_t j = 0; j < layer->tops.size(); j++)
  2157. {
  2158. int top_blob_index = layer->tops[j];
  2159. ncnn::Mat m;
  2160. ex.extract(top_blob_index, m);
  2161. blobs[top_blob_index].shape = m;
  2162. }
  2163. }
  2164. // assign all layer blob shape
  2165. for (size_t i = 0; i < layer_count; i++)
  2166. {
  2167. ncnn::Layer* layer = layers[i];
  2168. if (layer->type == "ncnnfused")
  2169. continue;
  2170. layer->bottom_shapes.resize(layer->bottoms.size());
  2171. for (size_t j = 0; j < layer->bottoms.size(); j++)
  2172. {
  2173. int bottom_blob_index = layer->bottoms[j];
  2174. layer->bottom_shapes[j] = blobs[bottom_blob_index].shape;
  2175. }
  2176. layer->top_shapes.resize(layer->tops.size());
  2177. for (size_t j = 0; j < layer->tops.size(); j++)
  2178. {
  2179. int top_blob_index = layer->tops[j];
  2180. layer->top_shapes[j] = blobs[top_blob_index].shape;
  2181. // 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());
  2182. }
  2183. }
  2184. return 0;
  2185. }
  2186. int NetOptimize::estimate_memory_footprint()
  2187. {
  2188. const size_t layer_count = layers.size();
  2189. const size_t blob_count = blobs.size();
  2190. MemoryFootprintAllocator allocator;
  2191. ncnn::Extractor ex = create_extractor();
  2192. ex.set_blob_allocator(&allocator);
  2193. ex.set_workspace_allocator(&allocator);
  2194. // prepare Input blobs
  2195. for (size_t i = 0; i < layer_count; i++)
  2196. {
  2197. const ncnn::Layer* layer = layers[i];
  2198. if (layer->type == "ncnnfused")
  2199. continue;
  2200. if (layer->type != "Input")
  2201. continue;
  2202. ncnn::Input* input = (ncnn::Input*)layer;
  2203. int w = input->w;
  2204. int h = input->h;
  2205. int c = input->c;
  2206. int dims = 0;
  2207. if (w == 0 && h == 0 && c == 0) dims = 0;
  2208. if (w != 0 && h == 0 && c == 0) dims = 1;
  2209. if (w != 0 && h != 0 && c == 0) dims = 2;
  2210. if (w != 0 && h != 0 && c != 0) dims = 3;
  2211. if (dims == 0)
  2212. {
  2213. fprintf(stderr, "Input layer %s without shape info, estimate_memory_footprint aborted\n", layer->name.c_str());
  2214. return -1;
  2215. }
  2216. ncnn::Mat m;
  2217. if (dims == 1) m.create(w, 4u, &allocator);
  2218. if (dims == 2) m.create(w, h, 4u, &allocator);
  2219. if (dims == 3) m.create(w, h, c, 4u, &allocator);
  2220. ex.input(layer->tops[0], m);
  2221. fprintf(stderr, "input = %s\n", blobs[layer->tops[0]].name.c_str());
  2222. }
  2223. // find output blobs and do inference
  2224. std::vector<ncnn::Mat> outputs;
  2225. for (size_t i = 0; i < blob_count; i++)
  2226. {
  2227. const ncnn::Blob& blob = blobs[i];
  2228. if (!blob.consumers.empty())
  2229. continue;
  2230. // treat blob without any consumers as output
  2231. ncnn::Mat m;
  2232. ex.extract(int(i), m);
  2233. outputs.push_back(m);
  2234. fprintf(stderr, "extract = %s\n", blob.name.c_str());
  2235. }
  2236. fprintf(stderr, "estimated memory footprint = %.2f KB = %.2f MB\n", allocator.memory_footprint / 1024.f, allocator.memory_footprint / 1024.f / 1024.f);
  2237. return 0;
  2238. }
  2239. int NetOptimize::fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp)
  2240. {
  2241. const int count = m.w;
  2242. const int* ptr = m;
  2243. fprintf(pp, " -%d=%d", 23300 + id, count);
  2244. for (int i = 0; i < count; i++)
  2245. {
  2246. fprintf(pp, ",%d", ptr[i]);
  2247. }
  2248. return 0;
  2249. }
  2250. int NetOptimize::fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp)
  2251. {
  2252. const int count = m.w;
  2253. const float* ptr = m;
  2254. fprintf(pp, " -%d=%d", 23300 + id, count);
  2255. for (int i = 0; i < count; i++)
  2256. {
  2257. fprintf(pp, ",%e", ptr[i]);
  2258. }
  2259. return 0;
  2260. }
  2261. static inline size_t alignSize(size_t sz, int n)
  2262. {
  2263. return (sz + n - 1) & -n;
  2264. }
  2265. int NetOptimize::fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp)
  2266. {
  2267. int p0 = ftell(bp);
  2268. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  2269. if (storage_type == 1 && tag == 0)
  2270. {
  2271. tag = 0x01306B47; // fp16 magic
  2272. fwrite(&tag, sizeof(int), 1, bp);
  2273. ncnn::Mat data_flattened_fp16;
  2274. ncnn::cast_float32_to_float16(data_flattened, data_flattened_fp16);
  2275. fwrite(data_flattened_fp16.data, data_flattened_fp16.elemsize, data_flattened_fp16.w, bp);
  2276. }
  2277. else
  2278. {
  2279. fwrite(&tag, sizeof(int), 1, bp);
  2280. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  2281. }
  2282. // padding to 32bit align
  2283. int nwrite = ftell(bp) - p0;
  2284. size_t nalign = alignSize(nwrite, 4);
  2285. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  2286. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  2287. return 0;
  2288. }
  2289. int NetOptimize::fwrite_weight_data(const ncnn::Mat& data, FILE* bp)
  2290. {
  2291. int p0 = ftell(bp);
  2292. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  2293. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  2294. // padding to 32bit align
  2295. int nwrite = ftell(bp) - p0;
  2296. size_t nalign = alignSize(nwrite, 4);
  2297. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  2298. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  2299. return 0;
  2300. }
  2301. int NetOptimize::save(const char* parampath, const char* binpath)
  2302. {
  2303. unsigned int mac = 0;
  2304. FILE* pp = fopen(parampath, "wb");
  2305. FILE* bp = fopen(binpath, "wb");
  2306. fprintf(pp, "7767517\n");
  2307. const size_t layer_count = layers.size();
  2308. int layer_count_fused = 0;
  2309. std::set<std::string> blob_names;
  2310. for (size_t i = 0; i < layer_count; i++)
  2311. {
  2312. const ncnn::Layer* layer = layers[i];
  2313. if (layer->type == "ncnnfused")
  2314. continue;
  2315. layer_count_fused++;
  2316. size_t bottom_count = layer->bottoms.size();
  2317. for (size_t j = 0; j < bottom_count; j++)
  2318. {
  2319. int bottom_blob_index = layer->bottoms[j];
  2320. blob_names.insert(blobs[bottom_blob_index].name);
  2321. }
  2322. size_t top_count = layer->tops.size();
  2323. for (size_t j = 0; j < top_count; j++)
  2324. {
  2325. int top_blob_index = layer->tops[j];
  2326. blob_names.insert(blobs[top_blob_index].name);
  2327. }
  2328. }
  2329. size_t blob_count_fused = blob_names.size();
  2330. fprintf(pp, "%d %zd\n", layer_count_fused, blob_count_fused);
  2331. for (size_t i = 0; i < layer_count; i++)
  2332. {
  2333. const ncnn::Layer* layer = layers[i];
  2334. if (layer->type == "ncnnfused")
  2335. continue;
  2336. size_t bottom_count = layer->bottoms.size();
  2337. size_t top_count = layer->tops.size();
  2338. fprintf(pp, "%-24s %-24s %zd %zd", layer->type.c_str(), layer->name.c_str(), bottom_count, top_count);
  2339. for (size_t j = 0; j < bottom_count; j++)
  2340. {
  2341. int bottom_blob_index = layer->bottoms[j];
  2342. fprintf(pp, " %s", blobs[bottom_blob_index].name.c_str());
  2343. }
  2344. for (size_t j = 0; j < top_count; j++)
  2345. {
  2346. int top_blob_index = layer->tops[j];
  2347. fprintf(pp, " %s", blobs[top_blob_index].name.c_str());
  2348. }
  2349. // write shape hints
  2350. bool shape_ready = true;
  2351. for (size_t j = 0; j < top_count; j++)
  2352. {
  2353. int top_blob_index = layer->tops[j];
  2354. int dims = blobs[top_blob_index].shape.dims;
  2355. if (dims == 0)
  2356. {
  2357. shape_ready = false;
  2358. break;
  2359. }
  2360. }
  2361. if (shape_ready)
  2362. {
  2363. fprintf(pp, " -23330=%zd", top_count * 4);
  2364. for (size_t j = 0; j < top_count; j++)
  2365. {
  2366. int top_blob_index = layer->tops[j];
  2367. int dims = blobs[top_blob_index].shape.dims;
  2368. int w = blobs[top_blob_index].shape.w;
  2369. int h = blobs[top_blob_index].shape.h;
  2370. int c = blobs[top_blob_index].shape.c;
  2371. fprintf(pp, ",%d,%d,%d,%d", dims, w, h, c);
  2372. }
  2373. }
  2374. ncnn::Layer* layer_default = ncnn::create_layer(layer->typeindex);
  2375. ncnn::ParamDict pd;
  2376. layer_default->load_param(pd);
  2377. #define fprintf_param_value(format, phase) \
  2378. { \
  2379. if (op->phase != op_default->phase) fprintf(pp, format, op->phase); \
  2380. }
  2381. if (layer->type == "BatchNorm")
  2382. {
  2383. ncnn::BatchNorm* op = (ncnn::BatchNorm*)layer;
  2384. ncnn::BatchNorm* op_default = (ncnn::BatchNorm*)layer_default;
  2385. fprintf_param_value(" 0=%d", channels)
  2386. fprintf_param_value(" 1=%e", eps)
  2387. fwrite_weight_data(op->slope_data, bp);
  2388. fwrite_weight_data(op->mean_data, bp);
  2389. fwrite_weight_data(op->var_data, bp);
  2390. fwrite_weight_data(op->bias_data, bp);
  2391. }
  2392. else if (layer->type == "Bias")
  2393. {
  2394. ncnn::Bias* op = (ncnn::Bias*)layer;
  2395. ncnn::Bias* op_default = (ncnn::Bias*)layer_default;
  2396. fprintf_param_value(" 0=%d", bias_data_size)
  2397. fwrite_weight_data(op->bias_data, bp);
  2398. }
  2399. else if (layer->type == "BinaryOp")
  2400. {
  2401. ncnn::BinaryOp* op = (ncnn::BinaryOp*)layer;
  2402. ncnn::BinaryOp* op_default = (ncnn::BinaryOp*)layer_default;
  2403. fprintf_param_value(" 0=%d", op_type)
  2404. fprintf_param_value(" 1=%d", with_scalar)
  2405. fprintf_param_value(" 2=%e", b)
  2406. }
  2407. else if (layer->type == "Clip")
  2408. {
  2409. ncnn::Clip* op = (ncnn::Clip*)layer;
  2410. ncnn::Clip* op_default = (ncnn::Clip*)layer_default;
  2411. fprintf_param_value(" 0=%e", min)
  2412. fprintf_param_value(" 1=%e", max)
  2413. }
  2414. else if (layer->type == "Concat")
  2415. {
  2416. ncnn::Concat* op = (ncnn::Concat*)layer;
  2417. ncnn::Concat* op_default = (ncnn::Concat*)layer_default;
  2418. fprintf_param_value(" 0=%d", axis)
  2419. }
  2420. else if (layer->type == "Convolution")
  2421. {
  2422. ncnn::Convolution* op = (ncnn::Convolution*)layer;
  2423. ncnn::Convolution* op_default = (ncnn::Convolution*)layer_default;
  2424. fprintf_param_value(" 0=%d", num_output)
  2425. fprintf_param_value(" 1=%d", kernel_w)
  2426. {
  2427. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2428. }
  2429. fprintf_param_value(" 2=%d", dilation_w)
  2430. {
  2431. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2432. }
  2433. fprintf_param_value(" 3=%d", stride_w)
  2434. {
  2435. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2436. }
  2437. fprintf_param_value(" 4=%d", pad_left)
  2438. {
  2439. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2440. }
  2441. {
  2442. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2443. }
  2444. {
  2445. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2446. }
  2447. fprintf_param_value(" 18=%e", pad_value)
  2448. fprintf_param_value(" 5=%d", bias_term)
  2449. fprintf_param_value(" 6=%d", weight_data_size)
  2450. fprintf_param_value(" 8=%d", int8_scale_term)
  2451. fprintf_param_value(" 9=%d", activation_type)
  2452. {
  2453. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2454. }
  2455. fprintf_param_value(" 17=%d", impl_type)
  2456. fwrite_weight_tag_data(0, op->weight_data, bp);
  2457. fwrite_weight_data(op->bias_data, bp);
  2458. if (shape_ready)
  2459. {
  2460. int inc = blobs[layer->bottoms[0]].shape.c;
  2461. int outw = blobs[layer->tops[0]].shape.w;
  2462. int outh = blobs[layer->tops[0]].shape.h;
  2463. int outc = blobs[layer->tops[0]].shape.c;
  2464. mac += op->kernel_h * op->kernel_w * outw * outh * outc * inc;
  2465. }
  2466. }
  2467. else if (layer->type == "ConvolutionDepthWise")
  2468. {
  2469. ncnn::ConvolutionDepthWise* op = (ncnn::ConvolutionDepthWise*)layer;
  2470. ncnn::ConvolutionDepthWise* op_default = (ncnn::ConvolutionDepthWise*)layer_default;
  2471. fprintf_param_value(" 0=%d", num_output)
  2472. fprintf_param_value(" 1=%d", kernel_w)
  2473. {
  2474. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2475. }
  2476. fprintf_param_value(" 2=%d", dilation_w)
  2477. {
  2478. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2479. }
  2480. fprintf_param_value(" 3=%d", stride_w)
  2481. {
  2482. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2483. }
  2484. fprintf_param_value(" 4=%d", pad_left)
  2485. {
  2486. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2487. }
  2488. {
  2489. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2490. }
  2491. {
  2492. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2493. }
  2494. fprintf_param_value(" 18=%e", pad_value)
  2495. fprintf_param_value(" 5=%d", bias_term)
  2496. fprintf_param_value(" 6=%d", weight_data_size)
  2497. fprintf_param_value(" 7=%d", group)
  2498. fprintf_param_value(" 8=%d", int8_scale_term)
  2499. fprintf_param_value(" 9=%d", activation_type)
  2500. {
  2501. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2502. }
  2503. fwrite_weight_tag_data(0, op->weight_data, bp);
  2504. fwrite_weight_data(op->bias_data, bp);
  2505. if (shape_ready)
  2506. {
  2507. int inc = blobs[layer->bottoms[0]].shape.c;
  2508. int outw = blobs[layer->tops[0]].shape.w;
  2509. int outh = blobs[layer->tops[0]].shape.h;
  2510. int outc = blobs[layer->tops[0]].shape.c;
  2511. mac += op->kernel_h * op->kernel_w * outw * outh * (outc / op->group) * (inc / op->group) * op->group;
  2512. }
  2513. }
  2514. else if (layer->type == "Crop")
  2515. {
  2516. ncnn::Crop* op = (ncnn::Crop*)layer;
  2517. ncnn::Crop* op_default = (ncnn::Crop*)layer_default;
  2518. fprintf_param_value(" 0=%d", woffset)
  2519. fprintf_param_value(" 1=%d", hoffset)
  2520. fprintf_param_value(" 2=%d", coffset)
  2521. fprintf_param_value(" 3=%d", outw)
  2522. fprintf_param_value(" 4=%d", outh)
  2523. fprintf_param_value(" 5=%d", outc)
  2524. fprintf_param_value(" 6=%d", woffset2)
  2525. fprintf_param_value(" 7=%d", hoffset2)
  2526. fprintf_param_value(" 8=%d", coffset2)
  2527. {
  2528. if (!op->starts.empty()) fprintf_param_int_array(9, op->starts, pp);
  2529. }
  2530. {
  2531. if (!op->ends.empty()) fprintf_param_int_array(10, op->ends, pp);
  2532. }
  2533. {
  2534. if (!op->axes.empty()) fprintf_param_int_array(11, op->axes, pp);
  2535. }
  2536. }
  2537. else if (layer->type == "Deconvolution")
  2538. {
  2539. ncnn::Deconvolution* op = (ncnn::Deconvolution*)layer;
  2540. ncnn::Deconvolution* op_default = (ncnn::Deconvolution*)layer_default;
  2541. fprintf_param_value(" 0=%d", num_output)
  2542. fprintf_param_value(" 1=%d", kernel_w)
  2543. {
  2544. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2545. }
  2546. fprintf_param_value(" 2=%d", dilation_w)
  2547. {
  2548. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2549. }
  2550. fprintf_param_value(" 3=%d", stride_w)
  2551. {
  2552. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2553. }
  2554. fprintf_param_value(" 4=%d", pad_left)
  2555. {
  2556. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2557. }
  2558. {
  2559. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2560. }
  2561. {
  2562. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2563. }
  2564. fprintf_param_value(" 18=%d", output_pad_right)
  2565. {
  2566. if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom);
  2567. }
  2568. fprintf_param_value(" 20=%d", output_w)
  2569. {
  2570. if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h);
  2571. }
  2572. fprintf_param_value(" 5=%d", bias_term)
  2573. fprintf_param_value(" 6=%d", weight_data_size)
  2574. fprintf_param_value(" 9=%d", activation_type)
  2575. {
  2576. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2577. }
  2578. fwrite_weight_tag_data(0, op->weight_data, bp);
  2579. fwrite_weight_data(op->bias_data, bp);
  2580. if (shape_ready)
  2581. {
  2582. int inw = blobs[layer->bottoms[0]].shape.w;
  2583. int inh = blobs[layer->bottoms[0]].shape.h;
  2584. int inc = blobs[layer->bottoms[0]].shape.c;
  2585. int outc = blobs[layer->tops[0]].shape.c;
  2586. mac += op->kernel_h * op->kernel_w * inw * inh * outc * inc;
  2587. }
  2588. }
  2589. else if (layer->type == "DeconvolutionDepthWise")
  2590. {
  2591. ncnn::DeconvolutionDepthWise* op = (ncnn::DeconvolutionDepthWise*)layer;
  2592. ncnn::DeconvolutionDepthWise* op_default = (ncnn::DeconvolutionDepthWise*)layer_default;
  2593. fprintf_param_value(" 0=%d", num_output)
  2594. fprintf_param_value(" 1=%d", kernel_w)
  2595. {
  2596. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2597. }
  2598. fprintf_param_value(" 2=%d", dilation_w)
  2599. {
  2600. if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h);
  2601. }
  2602. fprintf_param_value(" 3=%d", stride_w)
  2603. {
  2604. if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h);
  2605. }
  2606. fprintf_param_value(" 4=%d", pad_left)
  2607. {
  2608. if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top);
  2609. }
  2610. {
  2611. if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right);
  2612. }
  2613. {
  2614. if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom);
  2615. }
  2616. fprintf_param_value(" 18=%d", output_pad_right)
  2617. {
  2618. if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom);
  2619. }
  2620. fprintf_param_value(" 20=%d", output_w)
  2621. {
  2622. if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h);
  2623. }
  2624. fprintf_param_value(" 5=%d", bias_term)
  2625. fprintf_param_value(" 6=%d", weight_data_size)
  2626. fprintf_param_value(" 7=%d", group)
  2627. fprintf_param_value(" 9=%d", activation_type)
  2628. {
  2629. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2630. }
  2631. fwrite_weight_tag_data(0, op->weight_data, bp);
  2632. fwrite_weight_data(op->bias_data, bp);
  2633. if (shape_ready)
  2634. {
  2635. int inw = blobs[layer->bottoms[0]].shape.w;
  2636. int inh = blobs[layer->bottoms[0]].shape.h;
  2637. int inc = blobs[layer->bottoms[0]].shape.c;
  2638. int outc = blobs[layer->tops[0]].shape.c;
  2639. mac += op->kernel_h * op->kernel_w * inw * inh * (outc / op->group) * (inc / op->group) * op->group;
  2640. }
  2641. }
  2642. else if (layer->type == "DetectionOutput")
  2643. {
  2644. ncnn::DetectionOutput* op = (ncnn::DetectionOutput*)layer;
  2645. ncnn::DetectionOutput* op_default = (ncnn::DetectionOutput*)layer_default;
  2646. fprintf_param_value(" 0=%d", num_class)
  2647. fprintf_param_value(" 1=%e", nms_threshold)
  2648. fprintf_param_value(" 2=%d", nms_top_k)
  2649. fprintf_param_value(" 3=%d", keep_top_k)
  2650. fprintf_param_value(" 4=%e", confidence_threshold)
  2651. fprintf_param_value(" 5=%e", variances[0])
  2652. fprintf_param_value(" 6=%e", variances[1])
  2653. fprintf_param_value(" 7=%e", variances[2])
  2654. fprintf_param_value(" 8=%e", variances[3])
  2655. }
  2656. else if (layer->type == "Dropout")
  2657. {
  2658. ncnn::Dropout* op = (ncnn::Dropout*)layer;
  2659. ncnn::Dropout* op_default = (ncnn::Dropout*)layer_default;
  2660. fprintf_param_value(" 0=%e", scale)
  2661. }
  2662. else if (layer->type == "Eltwise")
  2663. {
  2664. ncnn::Eltwise* op = (ncnn::Eltwise*)layer;
  2665. ncnn::Eltwise* op_default = (ncnn::Eltwise*)layer_default;
  2666. fprintf_param_value(" 0=%d", op_type)
  2667. {
  2668. if (!op->coeffs.empty()) fprintf_param_float_array(1, op->coeffs, pp);
  2669. }
  2670. }
  2671. else if (layer->type == "ELU")
  2672. {
  2673. ncnn::ELU* op = (ncnn::ELU*)layer;
  2674. ncnn::ELU* op_default = (ncnn::ELU*)layer_default;
  2675. fprintf_param_value(" 0=%e", alpha)
  2676. }
  2677. else if (layer->type == "Exp")
  2678. {
  2679. ncnn::Exp* op = (ncnn::Exp*)layer;
  2680. ncnn::Exp* op_default = (ncnn::Exp*)layer_default;
  2681. fprintf_param_value(" 0=%e", base)
  2682. fprintf_param_value(" 1=%e", scale)
  2683. fprintf_param_value(" 2=%e", shift)
  2684. }
  2685. else if (layer->type == "ExpandDims")
  2686. {
  2687. ncnn::ExpandDims* op = (ncnn::ExpandDims*)layer;
  2688. ncnn::ExpandDims* op_default = (ncnn::ExpandDims*)layer_default;
  2689. fprintf_param_value(" 0=%d", expand_w)
  2690. fprintf_param_value(" 1=%d", expand_h)
  2691. fprintf_param_value(" 2=%d", expand_c)
  2692. {
  2693. if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp);
  2694. }
  2695. }
  2696. else if (layer->type == "Gemm")
  2697. {
  2698. ncnn::Gemm* op = (ncnn::Gemm*)layer;
  2699. ncnn::Gemm* op_default = (ncnn::Gemm*)layer_default;
  2700. fprintf_param_value(" 0=%e", alpha)
  2701. fprintf_param_value(" 1=%e", beta)
  2702. fprintf_param_value(" 2=%d", transA)
  2703. fprintf_param_value(" 3=%d", transB)
  2704. }
  2705. else if (layer->type == "GroupNorm")
  2706. {
  2707. ncnn::GroupNorm* op = (ncnn::GroupNorm*)layer;
  2708. ncnn::GroupNorm* op_default = (ncnn::GroupNorm*)layer_default;
  2709. fprintf_param_value(" 0=%d", group)
  2710. fprintf_param_value(" 1=%d", channels)
  2711. fprintf_param_value(" 2=%e", eps)
  2712. fprintf_param_value(" 3=%d", affine)
  2713. fwrite_weight_data(op->gamma_data, bp);
  2714. fwrite_weight_data(op->beta_data, bp);
  2715. }
  2716. else if (layer->type == "HardSigmoid")
  2717. {
  2718. ncnn::HardSigmoid* op = (ncnn::HardSigmoid*)layer;
  2719. ncnn::HardSigmoid* op_default = (ncnn::HardSigmoid*)layer_default;
  2720. fprintf_param_value(" 0=%e", alpha)
  2721. fprintf_param_value(" 1=%e", beta)
  2722. }
  2723. else if (layer->type == "HardSwish")
  2724. {
  2725. ncnn::HardSwish* op = (ncnn::HardSwish*)layer;
  2726. ncnn::HardSwish* op_default = (ncnn::HardSwish*)layer_default;
  2727. fprintf_param_value(" 0=%e", alpha)
  2728. fprintf_param_value(" 1=%e", beta)
  2729. }
  2730. else if (layer->type == "InnerProduct")
  2731. {
  2732. ncnn::InnerProduct* op = (ncnn::InnerProduct*)layer;
  2733. ncnn::InnerProduct* op_default = (ncnn::InnerProduct*)layer_default;
  2734. fprintf_param_value(" 0=%d", num_output)
  2735. fprintf_param_value(" 1=%d", bias_term)
  2736. fprintf_param_value(" 2=%d", weight_data_size)
  2737. fprintf_param_value(" 8=%d", int8_scale_term)
  2738. fprintf_param_value(" 9=%d", activation_type)
  2739. {
  2740. if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp);
  2741. }
  2742. fwrite_weight_tag_data(0, op->weight_data, bp);
  2743. fwrite_weight_data(op->bias_data, bp);
  2744. if (shape_ready)
  2745. {
  2746. int inw = blobs[layer->bottoms[0]].shape.w;
  2747. int inh = blobs[layer->bottoms[0]].shape.h;
  2748. int inc = blobs[layer->bottoms[0]].shape.c;
  2749. int outw = blobs[layer->tops[0]].shape.w;
  2750. mac += inw * inh * inc * outw;
  2751. }
  2752. }
  2753. else if (layer->type == "Input")
  2754. {
  2755. ncnn::Input* op = (ncnn::Input*)layer;
  2756. ncnn::Input* op_default = (ncnn::Input*)layer_default;
  2757. fprintf_param_value(" 0=%d", w)
  2758. fprintf_param_value(" 1=%d", h)
  2759. fprintf_param_value(" 2=%d", c)
  2760. }
  2761. else if (layer->type == "InstanceNorm")
  2762. {
  2763. ncnn::InstanceNorm* op = (ncnn::InstanceNorm*)layer;
  2764. ncnn::InstanceNorm* op_default = (ncnn::InstanceNorm*)layer_default;
  2765. fprintf_param_value(" 0=%d", channels)
  2766. fprintf_param_value(" 1=%e", eps)
  2767. fprintf_param_value(" 2=%d", affine)
  2768. fwrite_weight_data(op->gamma_data, bp);
  2769. fwrite_weight_data(op->beta_data, bp);
  2770. }
  2771. else if (layer->type == "Interp")
  2772. {
  2773. ncnn::Interp* op = (ncnn::Interp*)layer;
  2774. ncnn::Interp* op_default = (ncnn::Interp*)layer_default;
  2775. fprintf_param_value(" 0=%d", resize_type)
  2776. fprintf_param_value(" 1=%e", height_scale)
  2777. fprintf_param_value(" 2=%e", width_scale)
  2778. fprintf_param_value(" 3=%d", output_height)
  2779. fprintf_param_value(" 4=%d", output_width)
  2780. }
  2781. else if (layer->type == "Log")
  2782. {
  2783. ncnn::Log* op = (ncnn::Log*)layer;
  2784. ncnn::Log* op_default = (ncnn::Log*)layer_default;
  2785. fprintf_param_value(" 0=%e", base)
  2786. fprintf_param_value(" 1=%e", scale)
  2787. fprintf_param_value(" 2=%e", shift)
  2788. }
  2789. else if (layer->type == "LRN")
  2790. {
  2791. ncnn::LRN* op = (ncnn::LRN*)layer;
  2792. ncnn::LRN* op_default = (ncnn::LRN*)layer_default;
  2793. fprintf_param_value(" 0=%d", region_type)
  2794. fprintf_param_value(" 1=%d", local_size)
  2795. fprintf_param_value(" 2=%e", alpha)
  2796. fprintf_param_value(" 3=%e", beta)
  2797. fprintf_param_value(" 4=%e", bias)
  2798. }
  2799. else if (layer->type == "LSTM")
  2800. {
  2801. ncnn::LSTM* op = (ncnn::LSTM*)layer;
  2802. ncnn::LSTM* op_default = (ncnn::LSTM*)layer_default;
  2803. fprintf_param_value(" 0=%d", num_output)
  2804. fprintf_param_value(" 1=%d", weight_data_size)
  2805. fprintf_param_value(" 2=%d", direction)
  2806. fwrite_weight_tag_data(0, op->weight_xc_data, bp);
  2807. fwrite_weight_tag_data(0, op->bias_c_data, bp);
  2808. fwrite_weight_tag_data(0, op->weight_hc_data, bp);
  2809. }
  2810. else if (layer->type == "MemoryData")
  2811. {
  2812. ncnn::MemoryData* op = (ncnn::MemoryData*)layer;
  2813. ncnn::MemoryData* op_default = (ncnn::MemoryData*)layer_default;
  2814. fprintf_param_value(" 0=%d", w)
  2815. fprintf_param_value(" 1=%d", h)
  2816. fprintf_param_value(" 2=%d", c)
  2817. fwrite_weight_data(op->data, bp);
  2818. }
  2819. else if (layer->type == "MVN")
  2820. {
  2821. ncnn::MVN* op = (ncnn::MVN*)layer;
  2822. ncnn::MVN* op_default = (ncnn::MVN*)layer_default;
  2823. fprintf_param_value(" 0=%d", normalize_variance)
  2824. fprintf_param_value(" 1=%d", across_channels)
  2825. fprintf_param_value(" 2=%e", eps)
  2826. }
  2827. else if (layer->type == "Normalize")
  2828. {
  2829. ncnn::Normalize* op = (ncnn::Normalize*)layer;
  2830. ncnn::Normalize* op_default = (ncnn::Normalize*)layer_default;
  2831. fprintf_param_value(" 0=%d", across_spatial)
  2832. fprintf_param_value(" 1=%d", channel_shared)
  2833. fprintf_param_value(" 2=%e", eps)
  2834. fprintf_param_value(" 3=%d", scale_data_size)
  2835. fprintf_param_value(" 4=%d", across_channel)
  2836. fprintf_param_value(" 9=%d", eps_mode)
  2837. fwrite_weight_data(op->scale_data, bp);
  2838. }
  2839. else if (layer->type == "Padding")
  2840. {
  2841. ncnn::Padding* op = (ncnn::Padding*)layer;
  2842. ncnn::Padding* op_default = (ncnn::Padding*)layer_default;
  2843. fprintf_param_value(" 0=%d", top)
  2844. fprintf_param_value(" 1=%d", bottom)
  2845. fprintf_param_value(" 2=%d", left)
  2846. fprintf_param_value(" 3=%d", right)
  2847. fprintf_param_value(" 4=%d", type)
  2848. fprintf_param_value(" 5=%e", value)
  2849. fprintf_param_value(" 6=%d", per_channel_pad_data_size)
  2850. fprintf_param_value(" 7=%d", front)
  2851. fprintf_param_value(" 8=%d", behind)
  2852. }
  2853. else if (layer->type == "Permute")
  2854. {
  2855. ncnn::Permute* op = (ncnn::Permute*)layer;
  2856. ncnn::Permute* op_default = (ncnn::Permute*)layer_default;
  2857. fprintf_param_value(" 0=%d", order_type)
  2858. }
  2859. else if (layer->type == "PixelShuffle")
  2860. {
  2861. ncnn::PixelShuffle* op = (ncnn::PixelShuffle*)layer;
  2862. ncnn::PixelShuffle* op_default = (ncnn::PixelShuffle*)layer_default;
  2863. fprintf_param_value(" 0=%d", upscale_factor)
  2864. }
  2865. else if (layer->type == "Pooling")
  2866. {
  2867. ncnn::Pooling* op = (ncnn::Pooling*)layer;
  2868. ncnn::Pooling* op_default = (ncnn::Pooling*)layer_default;
  2869. fprintf_param_value(" 0=%d", pooling_type)
  2870. fprintf_param_value(" 1=%d", kernel_w)
  2871. {
  2872. if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h);
  2873. }
  2874. fprintf_param_value(" 2=%d", stride_w)
  2875. {
  2876. if (op->stride_h != op->stride_w) fprintf(pp, " 12=%d", op->stride_h);
  2877. }
  2878. fprintf_param_value(" 3=%d", pad_left)
  2879. {
  2880. if (op->pad_top != op->pad_left) fprintf(pp, " 13=%d", op->pad_top);
  2881. }
  2882. {
  2883. if (op->pad_right != op->pad_left) fprintf(pp, " 14=%d", op->pad_right);
  2884. }
  2885. {
  2886. if (op->pad_bottom != op->pad_top) fprintf(pp, " 15=%d", op->pad_bottom);
  2887. }
  2888. fprintf_param_value(" 4=%d", global_pooling)
  2889. fprintf_param_value(" 5=%d", pad_mode)
  2890. }
  2891. else if (layer->type == "Power")
  2892. {
  2893. ncnn::Power* op = (ncnn::Power*)layer;
  2894. ncnn::Power* op_default = (ncnn::Power*)layer_default;
  2895. fprintf_param_value(" 0=%e", power)
  2896. fprintf_param_value(" 1=%e", scale)
  2897. fprintf_param_value(" 2=%e", shift)
  2898. }
  2899. else if (layer->type == "PReLU")
  2900. {
  2901. ncnn::PReLU* op = (ncnn::PReLU*)layer;
  2902. ncnn::PReLU* op_default = (ncnn::PReLU*)layer_default;
  2903. fprintf_param_value(" 0=%d", num_slope)
  2904. fwrite_weight_data(op->slope_data, bp);
  2905. }
  2906. else if (layer->type == "PriorBox")
  2907. {
  2908. ncnn::PriorBox* op = (ncnn::PriorBox*)layer;
  2909. ncnn::PriorBox* op_default = (ncnn::PriorBox*)layer_default;
  2910. {
  2911. if (!op->min_sizes.empty()) fprintf_param_float_array(0, op->min_sizes, pp);
  2912. }
  2913. {
  2914. if (!op->max_sizes.empty()) fprintf_param_float_array(1, op->max_sizes, pp);
  2915. }
  2916. {
  2917. if (!op->aspect_ratios.empty()) fprintf_param_float_array(2, op->aspect_ratios, pp);
  2918. }
  2919. fprintf_param_value(" 3=%e", variances[0])
  2920. fprintf_param_value(" 4=%e", variances[1])
  2921. fprintf_param_value(" 5=%e", variances[2])
  2922. fprintf_param_value(" 6=%e", variances[3])
  2923. fprintf_param_value(" 7=%d", flip)
  2924. fprintf_param_value(" 8=%d", clip)
  2925. fprintf_param_value(" 9=%d", image_width)
  2926. fprintf_param_value(" 10=%d", image_height)
  2927. fprintf_param_value(" 11=%e", step_width)
  2928. fprintf_param_value(" 12=%e", step_height)
  2929. fprintf_param_value(" 13=%e", offset)
  2930. }
  2931. else if (layer->type == "Proposal")
  2932. {
  2933. ncnn::Proposal* op = (ncnn::Proposal*)layer;
  2934. ncnn::Proposal* op_default = (ncnn::Proposal*)layer_default;
  2935. fprintf_param_value(" 0=%d", feat_stride)
  2936. fprintf_param_value(" 1=%d", base_size)
  2937. fprintf_param_value(" 2=%d", pre_nms_topN)
  2938. fprintf_param_value(" 3=%d", after_nms_topN)
  2939. fprintf_param_value(" 4=%e", nms_thresh)
  2940. fprintf_param_value(" 5=%d", min_size)
  2941. }
  2942. else if (layer->type == "PSROIPooling")
  2943. {
  2944. ncnn::PSROIPooling* op = (ncnn::PSROIPooling*)layer;
  2945. ncnn::PSROIPooling* op_default = (ncnn::PSROIPooling*)layer_default;
  2946. fprintf_param_value(" 0=%d", pooled_width)
  2947. fprintf_param_value(" 1=%d", pooled_height)
  2948. fprintf_param_value(" 2=%e", spatial_scale)
  2949. fprintf_param_value(" 3=%d", output_dim)
  2950. }
  2951. else if (layer->type == "Quantize")
  2952. {
  2953. ncnn::Quantize* op = (ncnn::Quantize*)layer;
  2954. ncnn::Quantize* op_default = (ncnn::Quantize*)layer_default;
  2955. fprintf_param_value(" 0=%e", scale)
  2956. }
  2957. else if (layer->type == "Reduction")
  2958. {
  2959. ncnn::Reduction* op = (ncnn::Reduction*)layer;
  2960. ncnn::Reduction* op_default = (ncnn::Reduction*)layer_default;
  2961. fprintf_param_value(" 0=%d", operation)
  2962. fprintf_param_value(" 1=%d", reduce_all)
  2963. fprintf_param_value(" 2=%e", coeff)
  2964. {
  2965. if (!op->axes.empty()) fprintf_param_int_array(3, op->axes, pp);
  2966. }
  2967. fprintf_param_value(" 4=%d", keepdims)
  2968. }
  2969. else if (layer->type == "ReLU")
  2970. {
  2971. ncnn::ReLU* op = (ncnn::ReLU*)layer;
  2972. ncnn::ReLU* op_default = (ncnn::ReLU*)layer_default;
  2973. fprintf_param_value(" 0=%e", slope)
  2974. }
  2975. else if (layer->type == "Reorg")
  2976. {
  2977. ncnn::Reorg* op = (ncnn::Reorg*)layer;
  2978. ncnn::Reorg* op_default = (ncnn::Reorg*)layer_default;
  2979. fprintf_param_value(" 0=%d", stride)
  2980. }
  2981. else if (layer->type == "Requantize")
  2982. {
  2983. ncnn::Requantize* op = (ncnn::Requantize*)layer;
  2984. ncnn::Requantize* op_default = (ncnn::Requantize*)layer_default;
  2985. fprintf_param_value(" 0=%e", scale_in)
  2986. fprintf_param_value(" 1=%e", scale_out)
  2987. fprintf_param_value(" 2=%d", bias_term)
  2988. fprintf_param_value(" 3=%d", bias_data_size)
  2989. fprintf_param_value(" 4=%d", fusion_relu)
  2990. }
  2991. else if (layer->type == "Reshape")
  2992. {
  2993. ncnn::Reshape* op = (ncnn::Reshape*)layer;
  2994. ncnn::Reshape* op_default = (ncnn::Reshape*)layer_default;
  2995. fprintf_param_value(" 0=%d", w)
  2996. fprintf_param_value(" 1=%d", h)
  2997. fprintf_param_value(" 2=%d", c)
  2998. fprintf_param_value(" 3=%d", permute)
  2999. }
  3000. else if (layer->type == "ROIAlign")
  3001. {
  3002. ncnn::ROIAlign* op = (ncnn::ROIAlign*)layer;
  3003. ncnn::ROIAlign* op_default = (ncnn::ROIAlign*)layer_default;
  3004. fprintf_param_value(" 0=%d", pooled_width)
  3005. fprintf_param_value(" 1=%d", pooled_height)
  3006. fprintf_param_value(" 2=%e", spatial_scale)
  3007. fprintf_param_value(" 3=%d", sampling_ratio)
  3008. fprintf_param_value(" 4=%d", aligned)
  3009. fprintf_param_value(" 5=%d", version)
  3010. }
  3011. else if (layer->type == "ROIPooling")
  3012. {
  3013. ncnn::ROIPooling* op = (ncnn::ROIPooling*)layer;
  3014. ncnn::ROIPooling* op_default = (ncnn::ROIPooling*)layer_default;
  3015. fprintf_param_value(" 0=%d", pooled_width)
  3016. fprintf_param_value(" 1=%d", pooled_height)
  3017. fprintf_param_value(" 2=%e", spatial_scale)
  3018. }
  3019. else if (layer->type == "Scale")
  3020. {
  3021. ncnn::Scale* op = (ncnn::Scale*)layer;
  3022. ncnn::Scale* op_default = (ncnn::Scale*)layer_default;
  3023. fprintf_param_value(" 0=%d", scale_data_size)
  3024. fprintf_param_value(" 1=%d", bias_term)
  3025. fwrite_weight_data(op->scale_data, bp);
  3026. fwrite_weight_data(op->bias_data, bp);
  3027. }
  3028. else if (layer->type == "ShuffleChannel")
  3029. {
  3030. ncnn::ShuffleChannel* op = (ncnn::ShuffleChannel*)layer;
  3031. ncnn::ShuffleChannel* op_default = (ncnn::ShuffleChannel*)layer_default;
  3032. fprintf_param_value(" 0=%d", group)
  3033. }
  3034. else if (layer->type == "Slice")
  3035. {
  3036. ncnn::Slice* op = (ncnn::Slice*)layer;
  3037. ncnn::Slice* op_default = (ncnn::Slice*)layer_default;
  3038. {
  3039. if (!op->slices.empty()) fprintf_param_int_array(0, op->slices, pp);
  3040. }
  3041. fprintf_param_value(" 1=%d", axis)
  3042. }
  3043. else if (layer->type == "Softmax")
  3044. {
  3045. ncnn::Softmax* op = (ncnn::Softmax*)layer;
  3046. ncnn::Softmax* op_default = (ncnn::Softmax*)layer_default;
  3047. fprintf_param_value(" 0=%d", axis)
  3048. // HACK
  3049. if (op->axis != 0)
  3050. {
  3051. int fixbug0 = 1;
  3052. fprintf(pp, " 1=%d", fixbug0);
  3053. }
  3054. }
  3055. else if (layer->type == "Squeeze")
  3056. {
  3057. ncnn::Squeeze* op = (ncnn::Squeeze*)layer;
  3058. ncnn::Squeeze* op_default = (ncnn::Squeeze*)layer_default;
  3059. fprintf_param_value(" 0=%d", squeeze_w)
  3060. fprintf_param_value(" 1=%d", squeeze_h)
  3061. fprintf_param_value(" 2=%d", squeeze_c)
  3062. {
  3063. if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp);
  3064. }
  3065. }
  3066. else if (layer->type == "Threshold")
  3067. {
  3068. ncnn::Threshold* op = (ncnn::Threshold*)layer;
  3069. ncnn::Threshold* op_default = (ncnn::Threshold*)layer_default;
  3070. fprintf_param_value(" 0=%e", threshold)
  3071. }
  3072. else if (layer->type == "UnaryOp")
  3073. {
  3074. ncnn::UnaryOp* op = (ncnn::UnaryOp*)layer;
  3075. ncnn::UnaryOp* op_default = (ncnn::UnaryOp*)layer_default;
  3076. fprintf_param_value(" 0=%d", op_type)
  3077. }
  3078. else if (layer->type == "YoloDetectionOutput")
  3079. {
  3080. ncnn::YoloDetectionOutput* op = (ncnn::YoloDetectionOutput*)layer;
  3081. ncnn::YoloDetectionOutput* op_default = (ncnn::YoloDetectionOutput*)layer_default;
  3082. fprintf_param_value(" 0=%d", num_class)
  3083. fprintf_param_value(" 1=%d", num_box)
  3084. fprintf_param_value(" 2=%e", confidence_threshold)
  3085. fprintf_param_value(" 3=%e", nms_threshold)
  3086. {
  3087. if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp);
  3088. }
  3089. }
  3090. else if (layer->type == "Yolov3DetectionOutput")
  3091. {
  3092. ncnn::Yolov3DetectionOutput* op = (ncnn::Yolov3DetectionOutput*)layer;
  3093. ncnn::Yolov3DetectionOutput* op_default = (ncnn::Yolov3DetectionOutput*)layer_default;
  3094. fprintf_param_value(" 0=%d", num_class)
  3095. fprintf_param_value(" 1=%d", num_box)
  3096. fprintf_param_value(" 2=%e", confidence_threshold)
  3097. fprintf_param_value(" 3=%e", nms_threshold)
  3098. {
  3099. if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp);
  3100. }
  3101. {
  3102. if (!op->mask.empty()) fprintf_param_int_array(5, op->mask, pp);
  3103. }
  3104. {
  3105. if (!op->anchors_scale.empty()) fprintf_param_float_array(6, op->anchors_scale, pp);
  3106. }
  3107. }
  3108. #undef fprintf_param_value
  3109. fprintf(pp, "\n");
  3110. delete layer_default;
  3111. }
  3112. fclose(pp);
  3113. fclose(bp);
  3114. if (mac)
  3115. {
  3116. fprintf(stderr, "mac = %d = %.2f M\n", mac, mac / 1000000.f);
  3117. }
  3118. return 0;
  3119. }
  3120. int main(int argc, char** argv)
  3121. {
  3122. if (argc != 6)
  3123. {
  3124. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag]\n", argv[0]);
  3125. return -1;
  3126. }
  3127. const char* inparam = argv[1];
  3128. const char* inbin = argv[2];
  3129. const char* outparam = argv[3];
  3130. const char* outbin = argv[4];
  3131. int flag = atoi(argv[5]);
  3132. NetOptimize optimizer;
  3133. if (flag == 65536 || flag == 1)
  3134. {
  3135. optimizer.storage_type = 1;
  3136. }
  3137. else
  3138. {
  3139. optimizer.storage_type = 0;
  3140. }
  3141. optimizer.load_param(inparam);
  3142. if (strcmp(inbin, "null") == 0)
  3143. {
  3144. DataReaderFromEmpty dr;
  3145. optimizer.load_model(dr);
  3146. }
  3147. else
  3148. optimizer.load_model(inbin);
  3149. optimizer.fuse_batchnorm_scale();
  3150. optimizer.fuse_convolution_batchnorm();
  3151. optimizer.fuse_convolution_mul();
  3152. optimizer.fuse_convolution_add();
  3153. optimizer.fuse_convolutiondepthwise_batchnorm();
  3154. optimizer.fuse_convolutiondepthwise_mul();
  3155. optimizer.fuse_convolutiondepthwise_add();
  3156. optimizer.fuse_deconvolution_batchnorm();
  3157. optimizer.fuse_deconvolution_mul();
  3158. optimizer.fuse_deconvolution_add();
  3159. optimizer.fuse_deconvolutiondepthwise_batchnorm();
  3160. optimizer.fuse_innerproduct_batchnorm();
  3161. optimizer.fuse_innerproduct_add();
  3162. optimizer.fuse_innerproduct_dropout();
  3163. optimizer.replace_reduction_with_global_pooling();
  3164. optimizer.replace_prelu_with_leaky_relu();
  3165. optimizer.fuse_convolution_activation();
  3166. optimizer.fuse_convolutiondepthwise_activation();
  3167. optimizer.fuse_deconvolution_activation();
  3168. optimizer.fuse_deconvolutiondepthwise_activation();
  3169. optimizer.fuse_innerproduct_activation();
  3170. optimizer.fuse_memorydata_binaryop();
  3171. optimizer.fuse_binaryop_eltwise();
  3172. optimizer.eliminate_dropout();
  3173. optimizer.eliminate_pooling1x1();
  3174. optimizer.eliminate_noop();
  3175. optimizer.eliminate_flatten_after_global_pooling();
  3176. optimizer.eliminate_reshape_after_global_pooling();
  3177. optimizer.eliminate_reshape_before_binaryop();
  3178. optimizer.replace_convolution_with_innerproduct_after_global_pooling();
  3179. optimizer.replace_convolution_with_innerproduct_after_innerproduct();
  3180. optimizer.eliminate_flatten_after_innerproduct();
  3181. optimizer.eliminate_orphaned_memorydata();
  3182. optimizer.shape_inference();
  3183. optimizer.estimate_memory_footprint();
  3184. optimizer.save(outparam, outbin);
  3185. return 0;
  3186. }