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