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