You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ncnnoptimize.cpp 127 kB

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