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