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

ncnnoptimize.cpp 127 kB

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