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