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