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 90 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
7 years ago
7 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
6 years ago
7 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722
  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 "net.h"
  23. #include "layer.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/hardsigmoid.h"
  43. #include "layer/hardswish.h"
  44. #include "layer/innerproduct.h"
  45. #include "layer/input.h"
  46. #include "layer/instancenorm.h"
  47. #include "layer/interp.h"
  48. #include "layer/log.h"
  49. #include "layer/lrn.h"
  50. #include "layer/memorydata.h"
  51. #include "layer/mvn.h"
  52. #include "layer/normalize.h"
  53. #include "layer/padding.h"
  54. #include "layer/permute.h"
  55. #include "layer/pooling.h"
  56. #include "layer/power.h"
  57. #include "layer/prelu.h"
  58. #include "layer/priorbox.h"
  59. #include "layer/proposal.h"
  60. #include "layer/psroipooling.h"
  61. #include "layer/quantize.h"
  62. #include "layer/reduction.h"
  63. #include "layer/relu.h"
  64. #include "layer/reorg.h"
  65. #include "layer/requantize.h"
  66. #include "layer/reshape.h"
  67. #include "layer/roialign.h"
  68. #include "layer/roipooling.h"
  69. #include "layer/scale.h"
  70. #include "layer/slice.h"
  71. #include "layer/shufflechannel.h"
  72. #include "layer/softmax.h"
  73. #include "layer/squeeze.h"
  74. #include "layer/threshold.h"
  75. #include "layer/unaryop.h"
  76. #include "layer/yolodetectionoutput.h"
  77. #include "layer/yolov3detectionoutput.h"
  78. #if defined(__aarch64__) && defined(LINUX)
  79. #include <locale>
  80. #include <chrono>
  81. #include <random>
  82. #include <limits>
  83. #include <cassert>
  84. #define TEXT_GREEN "\033[32m"
  85. #define TEXT_YELLOW "\033[33m"
  86. #define TEXT_RED "\033[31m"
  87. #define CLR "\033[0m"
  88. #endif // defined(__aarch64__) && defined(LINUX)
  89. class DataReaderFromEmpty : public ncnn::DataReader
  90. {
  91. public:
  92. virtual int scan(const char* format, void* p) const { return 0; }
  93. virtual size_t read(void* /*buf*/, size_t size) const { return size; }
  94. };
  95. class NetOptimize : public ncnn::Net
  96. {
  97. public:
  98. // 0=fp32 1=fp16
  99. int storage_type;
  100. public:
  101. int fuse_batchnorm_scale();
  102. int fuse_convolution_batchnorm();
  103. int fuse_convolutiondepthwise_batchnorm();
  104. int fuse_deconvolution_batchnorm();
  105. int fuse_deconvolutiondepthwise_batchnorm();
  106. int fuse_innerproduct_batchnorm();
  107. int fuse_innerproduct_dropout();
  108. int fuse_convolution_activation();
  109. int fuse_convolutiondepthwise_activation();
  110. int fuse_deconvolution_activation();
  111. int fuse_deconvolutiondepthwise_activation();
  112. int fuse_innerproduct_activation();
  113. int eliminate_dropout();
  114. int eliminate_pooling1x1();
  115. int eliminate_noop();
  116. int eliminate_orphaned_memorydata();
  117. int eliminate_flatten_after_global_pooling();
  118. int eliminate_reshape_after_global_pooling();
  119. int eliminate_flatten_after_innerproduct();
  120. int eliminate_reshape_before_binaryop();
  121. int replace_convolution_with_innerproduct_after_global_pooling();
  122. int replace_convolution_with_innerproduct_after_innerproduct();
  123. int shape_inference();
  124. public:
  125. int fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp);
  126. int fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp);
  127. int fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp);
  128. int fwrite_weight_data(const ncnn::Mat& data, FILE* bp);
  129. int save(const char* parampath, const char* binpath);
  130. #if defined(__aarch64__) && defined(LINUX)
  131. void gauss_random(ncnn::Mat &m);
  132. void find_fastest_fp32_conv(const char* name, int w, int h, int c);
  133. int support_fp32_conv_type(const ncnn::Convolution* op, const ncnn::Mat& mat, const int type);
  134. #endif
  135. };
  136. #if defined(__aarch64__) && defined(LINUX)
  137. void NetOptimize::gauss_random(ncnn::Mat &m)
  138. {
  139. std::random_device rd;
  140. std::mt19937 gen(rd());
  141. std::normal_distribution<float> d(1.0f, 1.0f);
  142. int size = m.total();
  143. for (int i = 0; i < size; ++i)
  144. {
  145. m[i] = d(gen);
  146. }
  147. }
  148. void NetOptimize::find_fastest_fp32_conv(const char* dataname, int w, int h, int c)
  149. {
  150. ncnn::PoolAllocator allocator;
  151. allocator.clear();
  152. ncnn::Option opt;
  153. // embeded system generally use single thread
  154. opt.num_threads = 1;
  155. const size_t layer_count = layers.size();
  156. ncnn::Extractor ex = create_extractor();
  157. ncnn::Mat input(w, h, c);
  158. if (ex.input(dataname, input) < 0)
  159. {
  160. fprintf(stderr, "set input failed, check dataname.\n");
  161. return;
  162. }
  163. const char* IMPL_NAME[6] = {"baseline", "winograd", "pointwise", "im2col", "direct", "conv3x3s2"};
  164. for (int i = 0; i < layer_count; ++i)
  165. {
  166. ncnn::Layer* layer = layers[i];
  167. if (layer->type == "Convolution")
  168. {
  169. ncnn::Convolution* op = (ncnn::Convolution*)layer;
  170. ncnn::Mat bottom_blob;
  171. ncnn::Mat top_blob;
  172. ex.extract(layer->bottoms[0], bottom_blob);
  173. ex.extract(layer->tops[0], top_blob);
  174. if (bottom_blob.empty() || top_blob.empty())
  175. {
  176. continue;
  177. }
  178. ncnn::Mat weight_blob(op->kernel_w, op->kernel_h, bottom_blob.c * top_blob.c);
  179. fprintf(stdout, TEXT_GREEN "Input [w h nc]: %d %d %d\n" CLR, bottom_blob.w, bottom_blob.h, bottom_blob.c);
  180. fprintf(stdout, TEXT_GREEN "Kernel [w h nc]: %d %d %d\n" CLR, op->kernel_w, op->kernel_h, bottom_blob.c * top_blob.c);
  181. fprintf(stdout, TEXT_GREEN "Output [w h nc]: %d %d %d\n" CLR, top_blob.w, top_blob.h, top_blob.c);
  182. // randomize input and kernel
  183. gauss_random(bottom_blob);
  184. // try every implementation
  185. double min_cost = std::numeric_limits<double>::max();
  186. int best_type = 0;
  187. // how much conv implementation type ncnn has ?
  188. for (int type = 1; type <= 5; ++type)
  189. {
  190. int support = support_fp32_conv_type(op, bottom_blob, type);
  191. if (support < 1)
  192. {
  193. // implementation type mismatch convolution configuration, skip
  194. continue;
  195. }
  196. op->impl_type = type;
  197. auto start = std::chrono::high_resolution_clock::now();
  198. const int NREPEATS = 20;
  199. op->create_pipeline(opt);
  200. for (int repeat = 0; repeat < NREPEATS; ++repeat)
  201. {
  202. op->forward(top_blob, bottom_blob, opt);
  203. }
  204. op->destroy_pipeline(opt);
  205. auto stop = std::chrono::high_resolution_clock::now();
  206. double cur_cost = std::chrono::duration<double, std::micro>(stop-start).count() / NREPEATS;
  207. fprintf(stdout, TEXT_GREEN "%s cost %0.3lfms \n" CLR, IMPL_NAME[type], cur_cost/1000);
  208. if (cur_cost < min_cost)
  209. {
  210. min_cost = cur_cost;
  211. best_type = type;
  212. }
  213. }
  214. op->impl_type = best_type;
  215. fprintf(stdout, TEXT_YELLOW "%d: %s use %s \n\n" CLR, i, layer->name.c_str(), IMPL_NAME[op->impl_type]);
  216. }
  217. }
  218. }
  219. int NetOptimize::support_fp32_conv_type(const ncnn::Convolution* op, const ncnn::Mat& bottom, const int type)
  220. {
  221. // not baseline, then k_h == k_w and s_h == s_w
  222. // no dilation conv shall be allowed
  223. if (op->kernel_w != op->kernel_h ||
  224. op->stride_w != op->stride_h ||
  225. op->dilation_w != op->dilation_h ||
  226. op->dilation_h != 1)
  227. {
  228. return -1;
  229. }
  230. // (kernel, stride) in {(1, 1), (1, 2), (2, 1), (3, 1), (3, 2), (4, 4), (5, 1), (5, 2), (7, 1), (7, 2)}
  231. const int support_table[7][4] =
  232. {
  233. {1, 1, 0, 0},
  234. {1, 0, 0, 0},
  235. {1, 1, 0, 0},
  236. {0, 0, 0, 1},
  237. {1, 1, 0, 0},
  238. {0, 0, 0, 0},
  239. {1, 1, 0, 0}
  240. };
  241. // kernel_size x stride
  242. const int kernel = op->kernel_h,
  243. stride = op->stride_h;
  244. // if match prequisation
  245. switch(type)
  246. {
  247. case 1:
  248. // winograd
  249. if (kernel != 3 || stride != 1){
  250. return -1;
  251. }
  252. break;
  253. case 2:
  254. // pointwise
  255. // input_h == 1, input_w == 1, dilation == 1, stride == 1
  256. if (bottom.h != 1 || bottom.w != 1 || stride != 1)
  257. {
  258. return -1;
  259. }
  260. break;
  261. case 3:
  262. // im2col
  263. break;
  264. case 4:
  265. // direct conv
  266. if (support_table[kernel-1][stride-1] == 0)
  267. {
  268. return -1;
  269. }
  270. break;
  271. case 5:
  272. // conv3x3s2
  273. // kernel == 3 and stride == 2
  274. if (kernel != 3 || stride != 2)
  275. {
  276. return -1;
  277. }
  278. break;
  279. default:
  280. fprintf(stderr, TEXT_RED "unrecognize convolution impl type: %d" CLR, type);
  281. break;
  282. }
  283. return 1;
  284. }
  285. #endif // defined(__aarch64__) && defined(LINUX)
  286. int NetOptimize::fuse_batchnorm_scale()
  287. {
  288. const size_t layer_count = layers.size();
  289. for (int i=0; i<layer_count; i++)
  290. {
  291. if (layers[i]->type != "BatchNorm")
  292. continue;
  293. // BatchNorm - Scale
  294. int top_blob_index = layers[i]->tops[0];
  295. int j = i + 1;
  296. for (; j<layer_count; j++)
  297. {
  298. if (layers[j]->type != "Scale")
  299. continue;
  300. if (layers[j]->bottoms.size() != 1)
  301. continue;
  302. if (layers[j]->bottoms[0] == top_blob_index)
  303. break;
  304. }
  305. if (j == layer_count)
  306. continue;
  307. // fuse BatchNorm - Scale to BatchNorm
  308. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[i];
  309. ncnn::Scale* scale = (ncnn::Scale*)layers[j];
  310. fprintf(stderr, "fuse_batchnorm_scale %s %s\n", batchnorm->name.c_str(), scale->name.c_str());
  311. {
  312. // v = ((v - mean) / sqrt(var + eps) * slope + bias) * s + b
  313. // = (v - mean) / sqrt(var + eps) * (slope * s) + (bias * s + b)
  314. int channels = batchnorm->channels;
  315. float* slope = batchnorm->slope_data;
  316. float* bias = batchnorm->bias_data;
  317. for (int q=0; q<channels; q++)
  318. {
  319. slope[q] = slope[q] * scale->scale_data[q];
  320. if (scale->bias_term)
  321. bias[q] = bias[q] * scale->scale_data[q] + scale->bias_data[q];
  322. else
  323. bias[q] = bias[q] * scale->scale_data[q];
  324. }
  325. }
  326. int top_blob_index_final = scale->tops[0];
  327. batchnorm->tops[0] = top_blob_index_final;
  328. blobs[top_blob_index_final].producer = i;
  329. scale->type = "ncnnfused";
  330. }
  331. return 0;
  332. }
  333. int NetOptimize::fuse_convolution_batchnorm()
  334. {
  335. const size_t layer_count = layers.size();
  336. for (int i=0; i<layer_count; i++)
  337. {
  338. if (layers[i]->type != "Convolution")
  339. continue;
  340. // Convolution - BatchNorm
  341. int top_blob_index = layers[i]->tops[0];
  342. int j = i + 1;
  343. for (; j<layer_count; j++)
  344. {
  345. if (layers[j]->type != "BatchNorm")
  346. continue;
  347. if (layers[j]->bottoms.size() != 1)
  348. continue;
  349. if (layers[j]->bottoms[0] == top_blob_index)
  350. break;
  351. }
  352. if (j == layer_count)
  353. continue;
  354. // fuse Convolution - BatchNorm to Convolution
  355. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  356. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  357. fprintf(stderr, "fuse_convolution_batchnorm %s %s\n", convolution->name.c_str(), batchnorm->name.c_str());
  358. {
  359. int channels = batchnorm->channels;
  360. float eps = batchnorm->eps;
  361. // a = bias - slope * mean / sqrt(var + eps)
  362. // b = slope / sqrt(var + eps)
  363. // value = value * b + a
  364. std::vector<float> a(channels);
  365. std::vector<float> b(channels);
  366. for (int i=0; i<channels; i++)
  367. {
  368. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  369. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  370. b[i] = batchnorm->slope_data[i] / sqrt_var;
  371. }
  372. if (convolution->bias_term == 0)
  373. {
  374. // init bias as zero
  375. convolution->bias_term = 1;
  376. convolution->bias_data = ncnn::Mat(channels);
  377. convolution->bias_data.fill(0.f);
  378. }
  379. const int weight_per_outch = convolution->weight_data_size / channels;
  380. float* weight = convolution->weight_data;
  381. float* bias = convolution->bias_data;
  382. for (int i=0; i<channels; i++)
  383. {
  384. float* conv_weight_outch = weight + weight_per_outch * i;
  385. for (int j=0; j<weight_per_outch; j++)
  386. {
  387. conv_weight_outch[j] *= b[i];
  388. }
  389. bias[i] = bias[i] * b[i] + a[i];
  390. }
  391. }
  392. int top_blob_index_final = batchnorm->tops[0];
  393. convolution->tops[0] = top_blob_index_final;
  394. blobs[top_blob_index_final].producer = i;
  395. batchnorm->type = "ncnnfused";
  396. }
  397. return 0;
  398. }
  399. int NetOptimize::fuse_convolutiondepthwise_batchnorm()
  400. {
  401. const size_t layer_count = layers.size();
  402. for (int i=0; i<layer_count; i++)
  403. {
  404. if (layers[i]->type != "ConvolutionDepthWise")
  405. continue;
  406. // ConvolutionDepthWise - BatchNorm
  407. int top_blob_index = layers[i]->tops[0];
  408. int j = i + 1;
  409. for (; j<layer_count; j++)
  410. {
  411. if (layers[j]->type != "BatchNorm")
  412. continue;
  413. if (layers[j]->bottoms.size() != 1)
  414. continue;
  415. if (layers[j]->bottoms[0] == top_blob_index)
  416. break;
  417. }
  418. if (j == layer_count)
  419. continue;
  420. // fuse ConvolutionDepthWise - BatchNorm to ConvolutionDepthWise
  421. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  422. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  423. fprintf(stderr, "fuse_convolutiondepthwise_batchnorm %s %s\n", convolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  424. {
  425. int channels = batchnorm->channels;
  426. float eps = batchnorm->eps;
  427. // a = bias - slope * mean / sqrt(var + eps)
  428. // b = slope / sqrt(var + eps)
  429. // value = value * b + a
  430. std::vector<float> a(channels);
  431. std::vector<float> b(channels);
  432. for (int i=0; i<channels; i++)
  433. {
  434. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  435. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  436. b[i] = batchnorm->slope_data[i] / sqrt_var;
  437. }
  438. if (convolutiondepthwise->bias_term == 0)
  439. {
  440. // init bias as zero
  441. convolutiondepthwise->bias_term = 1;
  442. convolutiondepthwise->bias_data = ncnn::Mat(channels);
  443. convolutiondepthwise->bias_data.fill(0.f);
  444. }
  445. const int weight_per_outch = convolutiondepthwise->weight_data_size / channels;
  446. float* weight = convolutiondepthwise->weight_data;
  447. float* bias = convolutiondepthwise->bias_data;
  448. for (int i=0; i<channels; i++)
  449. {
  450. float* conv_weight_outch = weight + weight_per_outch * i;
  451. for (int j=0; j<weight_per_outch; j++)
  452. {
  453. conv_weight_outch[j] *= b[i];
  454. }
  455. bias[i] = bias[i] * b[i] + a[i];
  456. }
  457. }
  458. int top_blob_index_final = batchnorm->tops[0];
  459. convolutiondepthwise->tops[0] = top_blob_index_final;
  460. blobs[top_blob_index_final].producer = i;
  461. batchnorm->type = "ncnnfused";
  462. }
  463. return 0;
  464. }
  465. int NetOptimize::fuse_deconvolution_batchnorm()
  466. {
  467. const size_t layer_count = layers.size();
  468. for (int i=0; i<layer_count; i++)
  469. {
  470. if (layers[i]->type != "Deconvolution")
  471. continue;
  472. // Deconvolution - BatchNorm
  473. int top_blob_index = layers[i]->tops[0];
  474. int j = i + 1;
  475. for (; j<layer_count; j++)
  476. {
  477. if (layers[j]->type != "BatchNorm")
  478. continue;
  479. if (layers[j]->bottoms.size() != 1)
  480. continue;
  481. if (layers[j]->bottoms[0] == top_blob_index)
  482. break;
  483. }
  484. if (j == layer_count)
  485. continue;
  486. // fuse Deconvolution - BatchNorm to Deconvolution
  487. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  488. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  489. fprintf(stderr, "fuse_deconvolution_batchnorm %s %s\n", deconvolution->name.c_str(), batchnorm->name.c_str());
  490. {
  491. int channels = batchnorm->channels;
  492. float eps = batchnorm->eps;
  493. // a = bias - slope * mean / sqrt(var + eps)
  494. // b = slope / sqrt(var + eps)
  495. // value = value * b + a
  496. std::vector<float> a(channels);
  497. std::vector<float> b(channels);
  498. for (int i=0; i<channels; i++)
  499. {
  500. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  501. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  502. b[i] = batchnorm->slope_data[i] / sqrt_var;
  503. }
  504. if (deconvolution->bias_term == 0)
  505. {
  506. // init bias as zero
  507. deconvolution->bias_term = 1;
  508. deconvolution->bias_data = ncnn::Mat(channels);
  509. deconvolution->bias_data.fill(0.f);
  510. }
  511. const int weight_per_outch = deconvolution->weight_data_size / channels;
  512. float* weight = deconvolution->weight_data;
  513. float* bias = deconvolution->bias_data;
  514. for (int i=0; i<channels; i++)
  515. {
  516. float* conv_weight_outch = weight + weight_per_outch * i;
  517. for (int j=0; j<weight_per_outch; j++)
  518. {
  519. conv_weight_outch[j] *= b[i];
  520. }
  521. bias[i] = bias[i] * b[i] + a[i];
  522. }
  523. }
  524. int top_blob_index_final = batchnorm->tops[0];
  525. deconvolution->tops[0] = top_blob_index_final;
  526. blobs[top_blob_index_final].producer = i;
  527. batchnorm->type = "ncnnfused";
  528. }
  529. return 0;
  530. }
  531. int NetOptimize::fuse_deconvolutiondepthwise_batchnorm()
  532. {
  533. const size_t layer_count = layers.size();
  534. for (int i=0; i<layer_count; i++)
  535. {
  536. if (layers[i]->type != "DeconvolutionDepthWise")
  537. continue;
  538. // DeconvolutionDepthWise - BatchNorm
  539. int top_blob_index = layers[i]->tops[0];
  540. int j = i + 1;
  541. for (; j<layer_count; j++)
  542. {
  543. if (layers[j]->type != "BatchNorm")
  544. continue;
  545. if (layers[j]->bottoms.size() != 1)
  546. continue;
  547. if (layers[j]->bottoms[0] == top_blob_index)
  548. break;
  549. }
  550. if (j == layer_count)
  551. continue;
  552. // fuse DeconvolutionDepthWise - BatchNorm to DeconvolutionDepthWise
  553. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  554. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  555. fprintf(stderr, "fuse_deconvolutiondepthwise_batchnorm %s %s\n", deconvolutiondepthwise->name.c_str(), batchnorm->name.c_str());
  556. {
  557. int channels = batchnorm->channels;
  558. float eps = batchnorm->eps;
  559. // a = bias - slope * mean / sqrt(var + eps)
  560. // b = slope / sqrt(var + eps)
  561. // value = value * b + a
  562. std::vector<float> a(channels);
  563. std::vector<float> b(channels);
  564. for (int i=0; i<channels; i++)
  565. {
  566. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  567. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  568. b[i] = batchnorm->slope_data[i] / sqrt_var;
  569. }
  570. if (deconvolutiondepthwise->bias_term == 0)
  571. {
  572. // init bias as zero
  573. deconvolutiondepthwise->bias_term = 1;
  574. deconvolutiondepthwise->bias_data = ncnn::Mat(channels);
  575. deconvolutiondepthwise->bias_data.fill(0.f);
  576. }
  577. const int weight_per_outch = deconvolutiondepthwise->weight_data_size / channels;
  578. float* weight = deconvolutiondepthwise->weight_data;
  579. float* bias = deconvolutiondepthwise->bias_data;
  580. for (int i=0; i<channels; i++)
  581. {
  582. float* conv_weight_outch = weight + weight_per_outch * i;
  583. for (int j=0; j<weight_per_outch; j++)
  584. {
  585. conv_weight_outch[j] *= b[i];
  586. }
  587. bias[i] = bias[i] * b[i] + a[i];
  588. }
  589. }
  590. int top_blob_index_final = batchnorm->tops[0];
  591. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  592. blobs[top_blob_index_final].producer = i;
  593. batchnorm->type = "ncnnfused";
  594. }
  595. return 0;
  596. }
  597. int NetOptimize::fuse_innerproduct_batchnorm()
  598. {
  599. const size_t layer_count = layers.size();
  600. for (int i=0; i<layer_count; i++)
  601. {
  602. if (layers[i]->type != "InnerProduct")
  603. continue;
  604. // InnerProduct - BatchNorm
  605. int top_blob_index = layers[i]->tops[0];
  606. int j = i + 1;
  607. for (; j<layer_count; j++)
  608. {
  609. if (layers[j]->type != "BatchNorm")
  610. continue;
  611. if (layers[j]->bottoms.size() != 1)
  612. continue;
  613. if (layers[j]->bottoms[0] == top_blob_index)
  614. break;
  615. }
  616. if (j == layer_count)
  617. continue;
  618. // fuse InnerProduct - BatchNorm to InnerProduct
  619. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  620. ncnn::BatchNorm* batchnorm = (ncnn::BatchNorm*)layers[j];
  621. fprintf(stderr, "fuse_innerproduct_batchnorm %s %s\n", innerproduct->name.c_str(), batchnorm->name.c_str());
  622. {
  623. int channels = batchnorm->channels;
  624. float eps = batchnorm->eps;
  625. // a = bias - slope * mean / sqrt(var + eps)
  626. // b = slope / sqrt(var + eps)
  627. // value = value * b + a
  628. std::vector<float> a(channels);
  629. std::vector<float> b(channels);
  630. for (int i=0; i<channels; i++)
  631. {
  632. float sqrt_var = static_cast<float>(sqrt(batchnorm->var_data[i] + eps));
  633. a[i] = batchnorm->bias_data[i] - batchnorm->slope_data[i] * batchnorm->mean_data[i] / sqrt_var;
  634. b[i] = batchnorm->slope_data[i] / sqrt_var;
  635. }
  636. if (innerproduct->bias_term == 0)
  637. {
  638. // init bias as zero
  639. innerproduct->bias_term = 1;
  640. innerproduct->bias_data = ncnn::Mat(channels);
  641. innerproduct->bias_data.fill(0.f);
  642. }
  643. const int weight_per_outch = innerproduct->weight_data_size / channels;
  644. float* weight = innerproduct->weight_data;
  645. float* bias = innerproduct->bias_data;
  646. for (int i=0; i<channels; i++)
  647. {
  648. float* conv_weight_outch = weight + weight_per_outch * i;
  649. for (int j=0; j<weight_per_outch; j++)
  650. {
  651. conv_weight_outch[j] *= b[i];
  652. }
  653. bias[i] = bias[i] * b[i] + a[i];
  654. }
  655. }
  656. int top_blob_index_final = batchnorm->tops[0];
  657. innerproduct->tops[0] = top_blob_index_final;
  658. blobs[top_blob_index_final].producer = i;
  659. batchnorm->type = "ncnnfused";
  660. }
  661. return 0;
  662. }
  663. int NetOptimize::fuse_innerproduct_dropout()
  664. {
  665. const size_t layer_count = layers.size();
  666. for (int i=0; i<layer_count; i++)
  667. {
  668. if (layers[i]->type != "InnerProduct")
  669. continue;
  670. // InnerProduct - Dropout
  671. int top_blob_index = layers[i]->tops[0];
  672. int j = i + 1;
  673. for (; j<layer_count; j++)
  674. {
  675. if (layers[j]->type != "Dropout")
  676. continue;
  677. if (layers[j]->bottoms.size() != 1)
  678. continue;
  679. if (layers[j]->bottoms[0] == top_blob_index)
  680. break;
  681. }
  682. if (j == layer_count)
  683. continue;
  684. // fuse InnerProduct - Dropout to InnerProduct
  685. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  686. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[j];
  687. fprintf(stderr, "fuse_innerproduct_dropout %s %s\n", innerproduct->name.c_str(), dropout->name.c_str());
  688. float scale = dropout->scale;
  689. if (scale != 1.f)
  690. {
  691. const int num_output = innerproduct->num_output;
  692. const int weight_per_outch = innerproduct->weight_data_size / num_output;
  693. float* weight = innerproduct->weight_data;
  694. for (int i=0; i<num_output; i++)
  695. {
  696. float* conv_weight_outch = weight + weight_per_outch * i;
  697. for (int j=0; j<weight_per_outch; j++)
  698. {
  699. conv_weight_outch[j] *= scale;
  700. }
  701. }
  702. if (innerproduct->bias_term)
  703. {
  704. float* bias = innerproduct->bias_data;
  705. for (int i=0; i<num_output; i++)
  706. {
  707. bias[i] *= scale;
  708. }
  709. }
  710. }
  711. int top_blob_index_final = dropout->tops[0];
  712. innerproduct->tops[0] = top_blob_index_final;
  713. blobs[top_blob_index_final].producer = i;
  714. dropout->type = "ncnnfused";
  715. }
  716. return 0;
  717. }
  718. int NetOptimize::fuse_convolution_activation()
  719. {
  720. const size_t layer_count = layers.size();
  721. for (int i=0; i<layer_count; i++)
  722. {
  723. if (layers[i]->type != "Convolution")
  724. continue;
  725. // Convolution - Activation
  726. int top_blob_index = layers[i]->tops[0];
  727. int j = i + 1;
  728. for (; j<layer_count; j++)
  729. {
  730. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  731. continue;
  732. if (layers[j]->bottoms.size() != 1)
  733. continue;
  734. if (layers[j]->bottoms[0] == top_blob_index)
  735. break;
  736. }
  737. if (j == layer_count)
  738. continue;
  739. // fuse Convolution - Activation to Convolution
  740. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[i];
  741. ncnn::Layer* activation = layers[j];
  742. fprintf(stderr, "fuse_convolution_activation %s %s\n", convolution->name.c_str(), activation->name.c_str());
  743. if (activation->type == "ReLU")
  744. {
  745. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  746. if (relu->slope == 0.f)
  747. {
  748. convolution->activation_type = 1;
  749. }
  750. else
  751. {
  752. convolution->activation_type = 2;
  753. convolution->activation_params = ncnn::Mat(1);
  754. convolution->activation_params[0] = relu->slope;
  755. }
  756. }
  757. else if (activation->type == "Clip")
  758. {
  759. ncnn::Clip* clip = (ncnn::Clip*)activation;
  760. convolution->activation_type = 3;
  761. convolution->activation_params = ncnn::Mat(2);
  762. convolution->activation_params[0] = clip->min;
  763. convolution->activation_params[1] = clip->max;
  764. }
  765. else if (activation->type == "Sigmoid")
  766. {
  767. convolution->activation_type = 4;
  768. }
  769. int top_blob_index_final = activation->tops[0];
  770. convolution->tops[0] = top_blob_index_final;
  771. blobs[top_blob_index_final].producer = i;
  772. activation->type = "ncnnfused";
  773. }
  774. return 0;
  775. }
  776. int NetOptimize::fuse_convolutiondepthwise_activation()
  777. {
  778. const size_t layer_count = layers.size();
  779. for (int i=0; i<layer_count; i++)
  780. {
  781. if (layers[i]->type != "ConvolutionDepthWise")
  782. continue;
  783. // ConvolutionDepthWise - Activation
  784. int top_blob_index = layers[i]->tops[0];
  785. int j = i + 1;
  786. for (; j<layer_count; j++)
  787. {
  788. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  789. continue;
  790. if (layers[j]->bottoms.size() != 1)
  791. continue;
  792. if (layers[j]->bottoms[0] == top_blob_index)
  793. break;
  794. }
  795. if (j == layer_count)
  796. continue;
  797. // fuse ConvolutionDepthWise - Activation to ConvolutionDepthWise
  798. ncnn::ConvolutionDepthWise* convolutiondepthwise = (ncnn::ConvolutionDepthWise*)layers[i];
  799. ncnn::Layer* activation = layers[j];
  800. fprintf(stderr, "fuse_convolutiondepthwise_activation %s %s\n", convolutiondepthwise->name.c_str(), activation->name.c_str());
  801. if (activation->type == "ReLU")
  802. {
  803. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  804. if (relu->slope == 0.f)
  805. {
  806. convolutiondepthwise->activation_type = 1;
  807. }
  808. else
  809. {
  810. convolutiondepthwise->activation_type = 2;
  811. convolutiondepthwise->activation_params = ncnn::Mat(1);
  812. convolutiondepthwise->activation_params[0] = relu->slope;
  813. }
  814. }
  815. else if (activation->type == "Clip")
  816. {
  817. ncnn::Clip* clip = (ncnn::Clip*)activation;
  818. convolutiondepthwise->activation_type = 3;
  819. convolutiondepthwise->activation_params = ncnn::Mat(2);
  820. convolutiondepthwise->activation_params[0] = clip->min;
  821. convolutiondepthwise->activation_params[1] = clip->max;
  822. }
  823. else if (activation->type == "Sigmoid")
  824. {
  825. convolutiondepthwise->activation_type = 4;
  826. }
  827. int top_blob_index_final = activation->tops[0];
  828. convolutiondepthwise->tops[0] = top_blob_index_final;
  829. blobs[top_blob_index_final].producer = i;
  830. activation->type = "ncnnfused";
  831. }
  832. return 0;
  833. }
  834. int NetOptimize::fuse_deconvolution_activation()
  835. {
  836. const size_t layer_count = layers.size();
  837. for (int i=0; i<layer_count; i++)
  838. {
  839. if (layers[i]->type != "Deconvolution")
  840. continue;
  841. // Deconvolution - Activation
  842. int top_blob_index = layers[i]->tops[0];
  843. int j = i + 1;
  844. for (; j<layer_count; j++)
  845. {
  846. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  847. continue;
  848. if (layers[j]->bottoms.size() != 1)
  849. continue;
  850. if (layers[j]->bottoms[0] == top_blob_index)
  851. break;
  852. }
  853. if (j == layer_count)
  854. continue;
  855. // fuse Deconvolution - Activation to Deconvolution
  856. ncnn::Deconvolution* deconvolution = (ncnn::Deconvolution*)layers[i];
  857. ncnn::Layer* activation = layers[j];
  858. fprintf(stderr, "fuse_deconvolution_activation %s %s\n", deconvolution->name.c_str(), activation->name.c_str());
  859. if (activation->type == "ReLU")
  860. {
  861. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  862. if (relu->slope == 0.f)
  863. {
  864. deconvolution->activation_type = 1;
  865. }
  866. else
  867. {
  868. deconvolution->activation_type = 2;
  869. deconvolution->activation_params = ncnn::Mat(1);
  870. deconvolution->activation_params[0] = relu->slope;
  871. }
  872. }
  873. else if (activation->type == "Clip")
  874. {
  875. ncnn::Clip* clip = (ncnn::Clip*)activation;
  876. deconvolution->activation_type = 3;
  877. deconvolution->activation_params = ncnn::Mat(2);
  878. deconvolution->activation_params[0] = clip->min;
  879. deconvolution->activation_params[1] = clip->max;
  880. }
  881. else if (activation->type == "Sigmoid")
  882. {
  883. deconvolution->activation_type = 4;
  884. }
  885. int top_blob_index_final = activation->tops[0];
  886. deconvolution->tops[0] = top_blob_index_final;
  887. blobs[top_blob_index_final].producer = i;
  888. activation->type = "ncnnfused";
  889. }
  890. return 0;
  891. }
  892. int NetOptimize::fuse_deconvolutiondepthwise_activation()
  893. {
  894. const size_t layer_count = layers.size();
  895. for (int i=0; i<layer_count; i++)
  896. {
  897. if (layers[i]->type != "DeconvolutionDepthWise")
  898. continue;
  899. // DeconvolutionDepthWise - Activation
  900. int top_blob_index = layers[i]->tops[0];
  901. int j = i + 1;
  902. for (; j<layer_count; j++)
  903. {
  904. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  905. continue;
  906. if (layers[j]->bottoms.size() != 1)
  907. continue;
  908. if (layers[j]->bottoms[0] == top_blob_index)
  909. break;
  910. }
  911. if (j == layer_count)
  912. continue;
  913. // fuse DeconvolutionDepthWise - Activation to DeconvolutionDepthWise
  914. ncnn::DeconvolutionDepthWise* deconvolutiondepthwise = (ncnn::DeconvolutionDepthWise*)layers[i];
  915. ncnn::Layer* activation = layers[j];
  916. fprintf(stderr, "fuse_deconvolutiondepthwise_activation %s %s\n", deconvolutiondepthwise->name.c_str(), activation->name.c_str());
  917. if (activation->type == "ReLU")
  918. {
  919. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  920. if (relu->slope == 0.f)
  921. {
  922. deconvolutiondepthwise->activation_type = 1;
  923. }
  924. else
  925. {
  926. deconvolutiondepthwise->activation_type = 2;
  927. deconvolutiondepthwise->activation_params = ncnn::Mat(1);
  928. deconvolutiondepthwise->activation_params[0] = relu->slope;
  929. }
  930. }
  931. else if (activation->type == "Clip")
  932. {
  933. ncnn::Clip* clip = (ncnn::Clip*)activation;
  934. deconvolutiondepthwise->activation_type = 3;
  935. deconvolutiondepthwise->activation_params = ncnn::Mat(2);
  936. deconvolutiondepthwise->activation_params[0] = clip->min;
  937. deconvolutiondepthwise->activation_params[1] = clip->max;
  938. }
  939. else if (activation->type == "Sigmoid")
  940. {
  941. deconvolutiondepthwise->activation_type = 4;
  942. }
  943. int top_blob_index_final = activation->tops[0];
  944. deconvolutiondepthwise->tops[0] = top_blob_index_final;
  945. blobs[top_blob_index_final].producer = i;
  946. activation->type = "ncnnfused";
  947. }
  948. return 0;
  949. }
  950. int NetOptimize::fuse_innerproduct_activation()
  951. {
  952. const size_t layer_count = layers.size();
  953. for (int i=0; i<layer_count; i++)
  954. {
  955. if (layers[i]->type != "InnerProduct")
  956. continue;
  957. // InnerProduct - Activation
  958. int top_blob_index = layers[i]->tops[0];
  959. int j = i + 1;
  960. for (; j<layer_count; j++)
  961. {
  962. if (layers[j]->type != "ReLU" && layers[j]->type != "Clip" && layers[j]->type != "Sigmoid")
  963. continue;
  964. if (layers[j]->bottoms.size() != 1)
  965. continue;
  966. if (layers[j]->bottoms[0] == top_blob_index)
  967. break;
  968. }
  969. if (j == layer_count)
  970. continue;
  971. // fuse InnerProduct - Activation to InnerProduct
  972. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  973. ncnn::Layer* activation = layers[j];
  974. fprintf(stderr, "fuse_innerproduct_activation %s %s\n", innerproduct->name.c_str(), activation->name.c_str());
  975. if (activation->type == "ReLU")
  976. {
  977. ncnn::ReLU* relu = (ncnn::ReLU*)activation;
  978. if (relu->slope == 0.f)
  979. {
  980. innerproduct->activation_type = 1;
  981. }
  982. else
  983. {
  984. innerproduct->activation_type = 2;
  985. innerproduct->activation_params = ncnn::Mat(1);
  986. innerproduct->activation_params[0] = relu->slope;
  987. }
  988. }
  989. else if (activation->type == "Clip")
  990. {
  991. ncnn::Clip* clip = (ncnn::Clip*)activation;
  992. innerproduct->activation_type = 3;
  993. innerproduct->activation_params = ncnn::Mat(2);
  994. innerproduct->activation_params[0] = clip->min;
  995. innerproduct->activation_params[1] = clip->max;
  996. }
  997. else if (activation->type == "Sigmoid")
  998. {
  999. innerproduct->activation_type = 4;
  1000. }
  1001. int top_blob_index_final = activation->tops[0];
  1002. innerproduct->tops[0] = top_blob_index_final;
  1003. blobs[top_blob_index_final].producer = i;
  1004. activation->type = "ncnnfused";
  1005. }
  1006. return 0;
  1007. }
  1008. int NetOptimize::eliminate_dropout()
  1009. {
  1010. const size_t layer_count = layers.size();
  1011. for (int i=0; i<layer_count; i++)
  1012. {
  1013. if (layers[i]->type != "Dropout")
  1014. continue;
  1015. ncnn::Dropout* dropout = (ncnn::Dropout*)layers[i];
  1016. if (dropout->scale != 1.f)
  1017. continue;
  1018. // Any - Dropout
  1019. int bottom_blob_index = layers[i]->bottoms[0];
  1020. int j = i - 1;
  1021. for (; j>=0; j--)
  1022. {
  1023. if (layers[j]->type == "ncnnfused")
  1024. continue;
  1025. if (layers[j]->tops.size() != 1)
  1026. continue;
  1027. if (layers[j]->tops[0] == bottom_blob_index)
  1028. break;
  1029. }
  1030. if (j == -1)
  1031. continue;
  1032. ncnn::Layer* any = layers[j];
  1033. fprintf(stderr, "eliminate_dropout %s %s\n", any->name.c_str(), dropout->name.c_str());
  1034. int top_blob_index_final = dropout->tops[0];
  1035. any->tops[0] = top_blob_index_final;
  1036. blobs[top_blob_index_final].producer = j;
  1037. dropout->type = "ncnnfused";
  1038. }
  1039. return 0;
  1040. }
  1041. int NetOptimize::eliminate_pooling1x1()
  1042. {
  1043. const size_t layer_count = layers.size();
  1044. for (int i=0; i<layer_count; i++)
  1045. {
  1046. if (layers[i]->type != "Pooling")
  1047. continue;
  1048. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1049. if (pooling->pad_left != 0 || pooling->pad_right != 0 || pooling->pad_top != 0 || pooling->pad_bottom != 0)
  1050. continue;
  1051. if (pooling->kernel_w != 1 || pooling->kernel_h != 1 || pooling->stride_w != 1 || pooling->stride_h != 1)
  1052. continue;
  1053. if (pooling->global_pooling != 0)
  1054. continue;
  1055. // Any - Pooling
  1056. int bottom_blob_index = layers[i]->bottoms[0];
  1057. int top_i = -1;
  1058. int j = i - 1;
  1059. for (; j>=0; j--)
  1060. {
  1061. if (layers[j]->type == "ncnnfused")
  1062. continue;
  1063. for (int k=0; k<layers[j]->tops.size(); k++)
  1064. {
  1065. if (layers[j]->tops[k] == bottom_blob_index)
  1066. {
  1067. top_i = k;
  1068. break;
  1069. }
  1070. }
  1071. if (top_i != -1)
  1072. break;
  1073. }
  1074. if (j == -1)
  1075. continue;
  1076. ncnn::Layer* any = layers[j];
  1077. fprintf(stderr, "eliminate_pooling1x1 %s %s\n", any->name.c_str(), pooling->name.c_str());
  1078. int top_blob_index_final = pooling->tops[0];
  1079. any->tops[top_i] = top_blob_index_final;
  1080. blobs[top_blob_index_final].producer = j;
  1081. pooling->type = "ncnnfused";
  1082. }
  1083. return 0;
  1084. }
  1085. int NetOptimize::eliminate_noop()
  1086. {
  1087. const size_t layer_count = layers.size();
  1088. for (int i=0; i<layer_count; i++)
  1089. {
  1090. if (layers[i]->type != "Noop")
  1091. continue;
  1092. ncnn::Layer* noop = layers[i];
  1093. if (noop->bottoms.empty())
  1094. {
  1095. // Noop
  1096. fprintf(stderr, "eliminate_noop %s\n", noop->name.c_str());
  1097. size_t top_blob_count = noop->tops.size();
  1098. for (int k=0; k<top_blob_count; k++)
  1099. {
  1100. int top_blob_index_final = noop->tops[k];
  1101. blobs[top_blob_index_final].producer = -1;
  1102. }
  1103. noop->type = "ncnnfused";
  1104. continue;
  1105. }
  1106. // Any - Noop
  1107. int bottom_blob_index = layers[i]->bottoms[0];
  1108. int j = i - 1;
  1109. for (; j>=0; j--)
  1110. {
  1111. if (layers[j]->type == "ncnnfused")
  1112. continue;
  1113. if (layers[j]->tops.size() != 1)
  1114. continue;
  1115. if (layers[j]->tops[0] == bottom_blob_index)
  1116. break;
  1117. }
  1118. if (j == -1)
  1119. continue;
  1120. ncnn::Layer* any = layers[j];
  1121. fprintf(stderr, "eliminate_noop %s %s\n", any->name.c_str(), noop->name.c_str());
  1122. size_t top_blob_count = std::min(noop->tops.size(), any->tops.size());
  1123. for (int k=0; k<top_blob_count; k++)
  1124. {
  1125. int top_blob_index_final = noop->tops[k];
  1126. any->tops[k] = top_blob_index_final;
  1127. blobs[top_blob_index_final].producer = j;
  1128. }
  1129. noop->type = "ncnnfused";
  1130. }
  1131. return 0;
  1132. }
  1133. int NetOptimize::eliminate_orphaned_memorydata()
  1134. {
  1135. const size_t layer_count = layers.size();
  1136. for (int i=0; i<layer_count; i++)
  1137. {
  1138. if (layers[i]->type != "MemoryData")
  1139. continue;
  1140. // MemoryData - X
  1141. int top_blob_index = layers[i]->tops[0];
  1142. int j = i + 1;
  1143. for (; j<layer_count; j++)
  1144. {
  1145. if (layers[j]->type == "ncnnfused")
  1146. continue;
  1147. bool orphaned = true;
  1148. for (int k=0; k<layers[j]->bottoms.size(); k++)
  1149. {
  1150. if (layers[j]->bottoms[k] == top_blob_index)
  1151. {
  1152. orphaned = false;
  1153. break;
  1154. }
  1155. }
  1156. if (!orphaned)
  1157. break;
  1158. }
  1159. if (j < layer_count)
  1160. continue;
  1161. // assert orphaned == true
  1162. fprintf(stderr, "eliminate_orphaned_memorydata %s\n", layers[i]->name.c_str());
  1163. layers[i]->type = "ncnnfused";
  1164. }
  1165. return 0;
  1166. }
  1167. int NetOptimize::eliminate_reshape_after_global_pooling()
  1168. {
  1169. const size_t layer_count = layers.size();
  1170. for (int i=0; i<layer_count; i++)
  1171. {
  1172. if (layers[i]->type != "Pooling")
  1173. continue;
  1174. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1175. if (pooling->global_pooling == 0)
  1176. continue;
  1177. // Pooling - Reshape
  1178. int top_blob_index = layers[i]->tops[0];
  1179. int j = i + 1;
  1180. for (; j<layer_count; j++)
  1181. {
  1182. if (layers[j]->type != "Reshape")
  1183. continue;
  1184. if (layers[j]->bottoms.size() != 1)
  1185. continue;
  1186. if (layers[j]->bottoms[0] == top_blob_index)
  1187. break;
  1188. }
  1189. if (j == layer_count)
  1190. continue;
  1191. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[j];
  1192. if (reshape->h != -233 || reshape->c != -233 || reshape->permute != 0)
  1193. continue;
  1194. fprintf(stderr, "eliminate_reshape_after_global_pooling %s %s\n", pooling->name.c_str(), reshape->name.c_str());
  1195. int top_blob_index_final = reshape->tops[0];
  1196. pooling->tops[0] = top_blob_index_final;
  1197. blobs[top_blob_index_final].producer = i;
  1198. reshape->type = "ncnnfused";
  1199. }
  1200. return 0;
  1201. }
  1202. int NetOptimize::eliminate_flatten_after_global_pooling()
  1203. {
  1204. const size_t layer_count = layers.size();
  1205. for (int i=0; i<layer_count; i++)
  1206. {
  1207. if (layers[i]->type != "Pooling")
  1208. continue;
  1209. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1210. if (pooling->global_pooling == 0)
  1211. continue;
  1212. // Pooling - Flatten
  1213. int top_blob_index = layers[i]->tops[0];
  1214. int j = i + 1;
  1215. for (; j<layer_count; j++)
  1216. {
  1217. if (layers[j]->type != "Flatten")
  1218. continue;
  1219. if (layers[j]->bottoms.size() != 1)
  1220. continue;
  1221. if (layers[j]->bottoms[0] == top_blob_index)
  1222. break;
  1223. }
  1224. if (j == layer_count)
  1225. continue;
  1226. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1227. fprintf(stderr, "eliminate_flatten_after_global_pooling %s %s\n", pooling->name.c_str(), flatten->name.c_str());
  1228. int top_blob_index_final = flatten->tops[0];
  1229. pooling->tops[0] = top_blob_index_final;
  1230. blobs[top_blob_index_final].producer = i;
  1231. flatten->type = "ncnnfused";
  1232. }
  1233. return 0;
  1234. }
  1235. int NetOptimize::eliminate_flatten_after_innerproduct()
  1236. {
  1237. const size_t layer_count = layers.size();
  1238. for (int i=0; i<layer_count; i++)
  1239. {
  1240. if (layers[i]->type != "InnerProduct")
  1241. continue;
  1242. // InnerProduct - Flatten
  1243. int top_blob_index = layers[i]->tops[0];
  1244. int j = i + 1;
  1245. for (; j<layer_count; j++)
  1246. {
  1247. if (layers[j]->type != "Flatten")
  1248. continue;
  1249. if (layers[j]->bottoms.size() != 1)
  1250. continue;
  1251. if (layers[j]->bottoms[0] == top_blob_index)
  1252. break;
  1253. }
  1254. if (j == layer_count)
  1255. continue;
  1256. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1257. ncnn::Flatten* flatten = (ncnn::Flatten*)layers[j];
  1258. fprintf(stderr, "eliminate_flatten_after_innerproduct %s %s\n", innerproduct->name.c_str(), flatten->name.c_str());
  1259. int top_blob_index_final = flatten->tops[0];
  1260. innerproduct->tops[0] = top_blob_index_final;
  1261. blobs[top_blob_index_final].producer = i;
  1262. flatten->type = "ncnnfused";
  1263. }
  1264. return 0;
  1265. }
  1266. int NetOptimize::eliminate_reshape_before_binaryop()
  1267. {
  1268. const size_t layer_count = layers.size();
  1269. for (int i=0; i<layer_count; i++)
  1270. {
  1271. if (layers[i]->type != "Reshape")
  1272. continue;
  1273. ncnn::Reshape* reshape = (ncnn::Reshape*)layers[i];
  1274. if (reshape->w != 1 || reshape->h != 1 || reshape->permute != 0)
  1275. continue;
  1276. // Reshape - BinaryOp
  1277. int top_blob_index = layers[i]->tops[0];
  1278. int j = i + 1;
  1279. for (; j<layer_count; j++)
  1280. {
  1281. if (layers[j]->type != "BinaryOp")
  1282. continue;
  1283. if (layers[j]->bottoms.size() != 2)
  1284. continue;
  1285. if (layers[j]->bottoms[0] == top_blob_index || layers[j]->bottoms[1] == top_blob_index)
  1286. break;
  1287. }
  1288. if (j == layer_count)
  1289. continue;
  1290. ncnn::BinaryOp* binaryop = (ncnn::BinaryOp*)layers[j];
  1291. fprintf(stderr, "eliminate_reshape_before_binaryop %s %s\n", reshape->name.c_str(), binaryop->name.c_str());
  1292. int bottom_blob_index_final = reshape->bottoms[0];
  1293. if (layers[j]->bottoms[0] == top_blob_index)
  1294. binaryop->bottoms[0] = bottom_blob_index_final;
  1295. if (layers[j]->bottoms[1] == top_blob_index)
  1296. binaryop->bottoms[1] = bottom_blob_index_final;
  1297. blobs[bottom_blob_index_final].consumers.erase(std::find(blobs[bottom_blob_index_final].consumers.begin(), blobs[bottom_blob_index_final].consumers.end(), i));
  1298. blobs[bottom_blob_index_final].consumers.push_back(j);
  1299. reshape->type = "ncnnfused";
  1300. }
  1301. return 0;
  1302. }
  1303. int NetOptimize::replace_convolution_with_innerproduct_after_global_pooling()
  1304. {
  1305. const size_t layer_count = layers.size();
  1306. for (int i=0; i<layer_count; i++)
  1307. {
  1308. if (layers[i]->type != "Pooling")
  1309. continue;
  1310. ncnn::Pooling* pooling = (ncnn::Pooling*)layers[i];
  1311. if (pooling->global_pooling == 0)
  1312. continue;
  1313. // Pooling - Convolution
  1314. int top_blob_index = layers[i]->tops[0];
  1315. int j = i + 1;
  1316. for (; j<layer_count; j++)
  1317. {
  1318. if (layers[j]->type != "Convolution")
  1319. continue;
  1320. if (layers[j]->bottoms.size() != 1)
  1321. continue;
  1322. if (layers[j]->bottoms[0] == top_blob_index)
  1323. break;
  1324. }
  1325. if (j == layer_count)
  1326. continue;
  1327. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  1328. fprintf(stderr, "replace_convolution_with_innerproduct_after_global_pooling %s %s\n", pooling->name.c_str(), convolution->name.c_str());
  1329. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  1330. innerproduct->type = "InnerProduct";
  1331. innerproduct->name = convolution->name;
  1332. innerproduct->bottoms = convolution->bottoms;
  1333. innerproduct->tops = convolution->tops;
  1334. ncnn::ParamDict pd;
  1335. innerproduct->load_param(pd);
  1336. innerproduct->num_output = convolution->num_output;
  1337. innerproduct->bias_term = convolution->bias_term;
  1338. innerproduct->weight_data_size = convolution->weight_data_size;
  1339. innerproduct->weight_data = convolution->weight_data;
  1340. innerproduct->bias_data = convolution->bias_data;
  1341. innerproduct->activation_type = convolution->activation_type;
  1342. innerproduct->activation_params = convolution->activation_params;
  1343. layers[j] = innerproduct;
  1344. delete convolution;
  1345. }
  1346. return 0;
  1347. }
  1348. int NetOptimize::replace_convolution_with_innerproduct_after_innerproduct()
  1349. {
  1350. const size_t layer_count = layers.size();
  1351. for (;;)
  1352. {
  1353. bool replaced = false;
  1354. for (int i=0; i<layer_count; i++)
  1355. {
  1356. if (layers[i]->type != "InnerProduct")
  1357. continue;
  1358. // InnerProduct - Convolution
  1359. int top_blob_index = layers[i]->tops[0];
  1360. int j = i + 1;
  1361. for (; j<layer_count; j++)
  1362. {
  1363. if (layers[j]->type != "Convolution")
  1364. continue;
  1365. if (layers[j]->bottoms.size() != 1)
  1366. continue;
  1367. if (layers[j]->bottoms[0] == top_blob_index)
  1368. break;
  1369. }
  1370. if (j == layer_count)
  1371. continue;
  1372. ncnn::InnerProduct* innerproduct = (ncnn::InnerProduct*)layers[i];
  1373. ncnn::Convolution* convolution = (ncnn::Convolution*)layers[j];
  1374. fprintf(stderr, "replace_convolution_with_innerproduct_after_innerproduct %s %s\n", innerproduct->name.c_str(), convolution->name.c_str());
  1375. ncnn::InnerProduct* innerproduct2 = (ncnn::InnerProduct*)ncnn::create_layer("InnerProduct");
  1376. innerproduct2->type = "InnerProduct";
  1377. innerproduct2->name = convolution->name;
  1378. innerproduct2->bottoms = convolution->bottoms;
  1379. innerproduct2->tops = convolution->tops;
  1380. ncnn::ParamDict pd;
  1381. innerproduct2->load_param(pd);
  1382. innerproduct2->num_output = convolution->num_output;
  1383. innerproduct2->bias_term = convolution->bias_term;
  1384. innerproduct2->weight_data_size = convolution->weight_data_size;
  1385. innerproduct2->weight_data = convolution->weight_data;
  1386. innerproduct2->bias_data = convolution->bias_data;
  1387. innerproduct2->activation_type = convolution->activation_type;
  1388. innerproduct2->activation_params = convolution->activation_params;
  1389. layers[j] = innerproduct2;
  1390. delete convolution;
  1391. replaced = true;
  1392. }
  1393. if (!replaced)
  1394. break;
  1395. }
  1396. return 0;
  1397. }
  1398. int NetOptimize::shape_inference()
  1399. {
  1400. const size_t layer_count = layers.size();
  1401. const size_t blob_count = blobs.size();
  1402. ncnn::Extractor ex = create_extractor();
  1403. // prepare Input blobs
  1404. for (size_t i=0; i<layer_count; i++)
  1405. {
  1406. const ncnn::Layer* layer = layers[i];
  1407. if (layer->type == "ncnnfused")
  1408. continue;
  1409. if (layer->type != "Input")
  1410. continue;
  1411. ncnn::Input* input = (ncnn::Input*)layer;
  1412. int w = input->w;
  1413. int h = input->h;
  1414. int c = input->c;
  1415. int dims = 0;
  1416. if (w == 0 && h == 0 && c == 0) dims = 0;
  1417. if (w != 0 && h == 0 && c == 0) dims = 1;
  1418. if (w != 0 && h != 0 && c == 0) dims = 2;
  1419. if (w != 0 && h != 0 && c != 0) dims = 3;
  1420. if (dims == 0)
  1421. {
  1422. fprintf(stderr, "Input layer %s without shape info, shape_inference aborted\n", layer->name.c_str());
  1423. return -1;
  1424. }
  1425. ncnn::Mat m;
  1426. if (dims == 1) m.create(w);
  1427. if (dims == 2) m.create(w, h);
  1428. if (dims == 3) m.create(w, h, c);
  1429. ex.input(layer->tops[0], m);
  1430. }
  1431. // prepare blobs with predefined shape
  1432. for (size_t i=0; i<blob_count; i++)
  1433. {
  1434. const ncnn::Blob blob = blobs[i];
  1435. int dims = blob.shape.dims;
  1436. int w = blob.shape.w;
  1437. int h = blob.shape.h;
  1438. int c = blob.shape.c;
  1439. if (dims == 0)
  1440. continue;
  1441. ncnn::Mat m;
  1442. if (dims == 1) m.create(w);
  1443. if (dims == 2) m.create(w, h);
  1444. if (dims == 3) m.create(w, h, c);
  1445. ex.input(int(i), m);
  1446. }
  1447. fprintf(stderr, "shape_inference\n");
  1448. // resolve all layer output blob shape
  1449. for (size_t i=0; i<layer_count; i++)
  1450. {
  1451. const ncnn::Layer* layer = layers[i];
  1452. if (layer->type == "ncnnfused")
  1453. continue;
  1454. for (size_t j=0; j<layer->tops.size(); j++)
  1455. {
  1456. int top_blob_index = layer->tops[j];
  1457. ncnn::Mat m;
  1458. ex.extract(top_blob_index, m);
  1459. blobs[top_blob_index].shape = m.shape();
  1460. }
  1461. }
  1462. // assign all layer blob shape
  1463. for (size_t i=0; i<layer_count; i++)
  1464. {
  1465. ncnn::Layer* layer = layers[i];
  1466. if (layer->type == "ncnnfused")
  1467. continue;
  1468. layer->bottom_shapes.resize(layer->bottoms.size());
  1469. for (size_t j=0; j<layer->bottoms.size(); j++)
  1470. {
  1471. int bottom_blob_index = layer->bottoms[j];
  1472. layer->bottom_shapes[j] = blobs[bottom_blob_index].shape;
  1473. }
  1474. layer->top_shapes.resize(layer->tops.size());
  1475. for (size_t j=0; j<layer->tops.size(); j++)
  1476. {
  1477. int top_blob_index = layer->tops[j];
  1478. layer->top_shapes[j] = blobs[top_blob_index].shape;
  1479. // 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());
  1480. }
  1481. }
  1482. return 0;
  1483. }
  1484. int NetOptimize::fprintf_param_int_array(int id, const ncnn::Mat& m, FILE* pp)
  1485. {
  1486. const int count = m.w;
  1487. const int* ptr = m;
  1488. fprintf(pp, " -%d=%d", 23300 + id, count);
  1489. for (int i=0; i<count; i++)
  1490. {
  1491. fprintf(pp, ",%d", ptr[i]);
  1492. }
  1493. return 0;
  1494. }
  1495. int NetOptimize::fprintf_param_float_array(int id, const ncnn::Mat& m, FILE* pp)
  1496. {
  1497. const int count = m.w;
  1498. const float* ptr = m;
  1499. fprintf(pp, " -%d=%d", 23300 + id, count);
  1500. for (int i=0; i<count; i++)
  1501. {
  1502. fprintf(pp, ",%e", ptr[i]);
  1503. }
  1504. return 0;
  1505. }
  1506. static inline size_t alignSize(size_t sz, int n)
  1507. {
  1508. return (sz + n-1) & -n;
  1509. }
  1510. int NetOptimize::fwrite_weight_tag_data(int tag, const ncnn::Mat& data, FILE* bp)
  1511. {
  1512. int p0 = ftell(bp);
  1513. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  1514. if (storage_type == 1 && tag == 0)
  1515. {
  1516. tag = 0x01306B47; // fp16 magic
  1517. fwrite(&tag, sizeof(int), 1, bp);
  1518. ncnn::Mat data_flattened_fp16;
  1519. ncnn::cast_float32_to_float16(data_flattened, data_flattened_fp16);
  1520. fwrite(data_flattened_fp16.data, data_flattened_fp16.elemsize, data_flattened_fp16.w, bp);
  1521. }
  1522. else
  1523. {
  1524. fwrite(&tag, sizeof(int), 1, bp);
  1525. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  1526. }
  1527. // padding to 32bit align
  1528. int nwrite = ftell(bp) - p0;
  1529. size_t nalign = alignSize(nwrite, 4);
  1530. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  1531. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  1532. return 0;
  1533. }
  1534. int NetOptimize::fwrite_weight_data(const ncnn::Mat& data, FILE* bp)
  1535. {
  1536. int p0 = ftell(bp);
  1537. ncnn::Mat data_flattened = data.reshape(data.w * data.h * data.c);
  1538. fwrite(data_flattened.data, data_flattened.elemsize, data_flattened.w, bp);
  1539. // padding to 32bit align
  1540. int nwrite = ftell(bp) - p0;
  1541. size_t nalign = alignSize(nwrite, 4);
  1542. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  1543. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  1544. return 0;
  1545. }
  1546. int NetOptimize::save(const char* parampath, const char* binpath)
  1547. {
  1548. FILE* pp = fopen(parampath, "wb");
  1549. FILE* bp = fopen(binpath, "wb");
  1550. fprintf(pp, "7767517\n");
  1551. const size_t layer_count = layers.size();
  1552. int layer_count_fused = 0;
  1553. std::set<std::string> blob_names;
  1554. for (int i=0; i<layer_count; i++)
  1555. {
  1556. const ncnn::Layer* layer = layers[i];
  1557. if (layer->type == "ncnnfused")
  1558. continue;
  1559. layer_count_fused++;
  1560. size_t bottom_count = layer->bottoms.size();
  1561. for (int j=0; j<bottom_count; j++)
  1562. {
  1563. int bottom_blob_index = layer->bottoms[j];
  1564. blob_names.insert(blobs[bottom_blob_index].name);
  1565. }
  1566. size_t top_count = layer->tops.size();
  1567. for (int j=0; j<top_count; j++)
  1568. {
  1569. int top_blob_index = layer->tops[j];
  1570. blob_names.insert(blobs[top_blob_index].name);
  1571. }
  1572. }
  1573. size_t blob_count_fused = blob_names.size();
  1574. fprintf(pp, "%d %zd\n", layer_count_fused, blob_count_fused);
  1575. for (int i=0; i<layer_count; i++)
  1576. {
  1577. const ncnn::Layer* layer = layers[i];
  1578. if (layer->type == "ncnnfused")
  1579. continue;
  1580. size_t bottom_count = layer->bottoms.size();
  1581. size_t top_count = layer->tops.size();
  1582. fprintf(pp, "%-24s %-24s %zd %zd", layer->type.c_str(), layer->name.c_str(), bottom_count, top_count);
  1583. for (int j=0; j<bottom_count; j++)
  1584. {
  1585. int bottom_blob_index = layer->bottoms[j];
  1586. fprintf(pp, " %s", blobs[bottom_blob_index].name.c_str());
  1587. }
  1588. for (int j=0; j<top_count; j++)
  1589. {
  1590. int top_blob_index = layer->tops[j];
  1591. fprintf(pp, " %s", blobs[top_blob_index].name.c_str());
  1592. }
  1593. // write shape hints
  1594. bool shape_ready = true;
  1595. for (int j=0; j<top_count; j++)
  1596. {
  1597. int top_blob_index = layer->tops[j];
  1598. int dims = blobs[top_blob_index].shape.dims;
  1599. if (dims == 0)
  1600. {
  1601. shape_ready = false;
  1602. break;
  1603. }
  1604. }
  1605. if (shape_ready)
  1606. {
  1607. fprintf(pp, " -23330=%zd", top_count * 4);
  1608. for (int j=0; j<top_count; j++)
  1609. {
  1610. int top_blob_index = layer->tops[j];
  1611. int dims = blobs[top_blob_index].shape.dims;
  1612. int w = blobs[top_blob_index].shape.w;
  1613. int h = blobs[top_blob_index].shape.h;
  1614. int c = blobs[top_blob_index].shape.c;
  1615. fprintf(pp, ",%d,%d,%d,%d", dims, w, h, c);
  1616. }
  1617. }
  1618. ncnn::Layer* layer_default = ncnn::create_layer(layer->typeindex);
  1619. ncnn::ParamDict pd;
  1620. layer_default->load_param(pd);
  1621. #define fprintf_param_value(format, phase) \
  1622. { if (op->phase != op_default->phase) fprintf(pp, format, op->phase); }
  1623. if (layer->type == "BatchNorm")
  1624. {
  1625. ncnn::BatchNorm* op = (ncnn::BatchNorm*)layer;
  1626. ncnn::BatchNorm* op_default = (ncnn::BatchNorm*)layer_default;
  1627. fprintf_param_value(" 0=%d", channels)
  1628. fprintf_param_value(" 1=%e", eps)
  1629. fwrite_weight_data(op->slope_data, bp);
  1630. fwrite_weight_data(op->mean_data, bp);
  1631. fwrite_weight_data(op->var_data, bp);
  1632. fwrite_weight_data(op->bias_data, bp);
  1633. }
  1634. else if (layer->type == "Bias")
  1635. {
  1636. ncnn::Bias* op = (ncnn::Bias*)layer;
  1637. ncnn::Bias* op_default = (ncnn::Bias*)layer_default;
  1638. fprintf_param_value(" 0=%d", bias_data_size)
  1639. fwrite_weight_data(op->bias_data, bp);
  1640. }
  1641. else if (layer->type == "BinaryOp")
  1642. {
  1643. ncnn::BinaryOp* op = (ncnn::BinaryOp*)layer;
  1644. ncnn::BinaryOp* op_default = (ncnn::BinaryOp*)layer_default;
  1645. fprintf_param_value(" 0=%d", op_type)
  1646. fprintf_param_value(" 1=%d", with_scalar)
  1647. fprintf_param_value(" 2=%e", b)
  1648. }
  1649. else if (layer->type == "Clip")
  1650. {
  1651. ncnn::Clip* op = (ncnn::Clip*)layer;
  1652. ncnn::Clip* op_default = (ncnn::Clip*)layer_default;
  1653. fprintf_param_value(" 0=%e", min)
  1654. fprintf_param_value(" 1=%e", max)
  1655. }
  1656. else if (layer->type == "Concat")
  1657. {
  1658. ncnn::Concat* op = (ncnn::Concat*)layer;
  1659. ncnn::Concat* op_default = (ncnn::Concat*)layer_default;
  1660. fprintf_param_value(" 0=%d", axis)
  1661. }
  1662. else if (layer->type == "Convolution")
  1663. {
  1664. ncnn::Convolution* op = (ncnn::Convolution*)layer;
  1665. ncnn::Convolution* op_default = (ncnn::Convolution*)layer_default;
  1666. fprintf_param_value(" 0=%d", num_output)
  1667. fprintf_param_value(" 1=%d", kernel_w)
  1668. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1669. fprintf_param_value(" 2=%d", dilation_w)
  1670. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1671. fprintf_param_value(" 3=%d", stride_w)
  1672. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1673. fprintf_param_value(" 4=%d", pad_left)
  1674. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1675. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1676. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1677. fprintf_param_value(" 18=%e", pad_value)
  1678. fprintf_param_value(" 5=%d", bias_term)
  1679. fprintf_param_value(" 6=%d", weight_data_size)
  1680. fprintf_param_value(" 8=%d", int8_scale_term)
  1681. fprintf_param_value(" 9=%d", activation_type)
  1682. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1683. fprintf_param_value(" 17=%d", impl_type)
  1684. fwrite_weight_tag_data(0, op->weight_data, bp);
  1685. fwrite_weight_data(op->bias_data, bp);
  1686. }
  1687. else if (layer->type == "ConvolutionDepthWise")
  1688. {
  1689. ncnn::ConvolutionDepthWise* op = (ncnn::ConvolutionDepthWise*)layer;
  1690. ncnn::ConvolutionDepthWise* op_default = (ncnn::ConvolutionDepthWise*)layer_default;
  1691. fprintf_param_value(" 0=%d", num_output)
  1692. fprintf_param_value(" 1=%d", kernel_w)
  1693. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1694. fprintf_param_value(" 2=%d", dilation_w)
  1695. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1696. fprintf_param_value(" 3=%d", stride_w)
  1697. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1698. fprintf_param_value(" 4=%d", pad_left)
  1699. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1700. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1701. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1702. fprintf_param_value(" 18=%e", pad_value)
  1703. fprintf_param_value(" 5=%d", bias_term)
  1704. fprintf_param_value(" 6=%d", weight_data_size)
  1705. fprintf_param_value(" 7=%d", group)
  1706. fprintf_param_value(" 8=%d", int8_scale_term)
  1707. fprintf_param_value(" 9=%d", activation_type)
  1708. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1709. fwrite_weight_tag_data(0, op->weight_data, bp);
  1710. fwrite_weight_data(op->bias_data, bp);
  1711. }
  1712. else if (layer->type == "Crop")
  1713. {
  1714. ncnn::Crop* op = (ncnn::Crop*)layer;
  1715. ncnn::Crop* op_default = (ncnn::Crop*)layer_default;
  1716. fprintf_param_value(" 0=%d", woffset)
  1717. fprintf_param_value(" 1=%d", hoffset)
  1718. fprintf_param_value(" 2=%d", coffset)
  1719. fprintf_param_value(" 3=%d", outw)
  1720. fprintf_param_value(" 4=%d", outh)
  1721. fprintf_param_value(" 5=%d", outc)
  1722. fprintf_param_value(" 6=%d", woffset2)
  1723. fprintf_param_value(" 7=%d", hoffset2)
  1724. fprintf_param_value(" 8=%d", coffset2)
  1725. { if (!op->starts.empty()) fprintf_param_int_array(9, op->starts, pp); }
  1726. { if (!op->ends.empty()) fprintf_param_int_array(10, op->ends, pp); }
  1727. { if (!op->axes.empty()) fprintf_param_int_array(11, op->axes, pp); }
  1728. }
  1729. else if (layer->type == "Deconvolution")
  1730. {
  1731. ncnn::Deconvolution* op = (ncnn::Deconvolution*)layer;
  1732. ncnn::Deconvolution* op_default = (ncnn::Deconvolution*)layer_default;
  1733. fprintf_param_value(" 0=%d", num_output)
  1734. fprintf_param_value(" 1=%d", kernel_w)
  1735. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1736. fprintf_param_value(" 2=%d", dilation_w)
  1737. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1738. fprintf_param_value(" 3=%d", stride_w)
  1739. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1740. fprintf_param_value(" 4=%d", pad_left)
  1741. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1742. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1743. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1744. fprintf_param_value(" 18=%d", output_pad_right)
  1745. { if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom); }
  1746. fprintf_param_value(" 20=%d", output_w)
  1747. { if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h); }
  1748. fprintf_param_value(" 5=%d", bias_term)
  1749. fprintf_param_value(" 6=%d", weight_data_size)
  1750. fprintf_param_value(" 9=%d", activation_type)
  1751. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1752. fwrite_weight_tag_data(0, op->weight_data, bp);
  1753. fwrite_weight_data(op->bias_data, bp);
  1754. }
  1755. else if (layer->type == "DeconvolutionDepthWise")
  1756. {
  1757. ncnn::DeconvolutionDepthWise* op = (ncnn::DeconvolutionDepthWise*)layer;
  1758. ncnn::DeconvolutionDepthWise* op_default = (ncnn::DeconvolutionDepthWise*)layer_default;
  1759. fprintf_param_value(" 0=%d", num_output)
  1760. fprintf_param_value(" 1=%d", kernel_w)
  1761. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1762. fprintf_param_value(" 2=%d", dilation_w)
  1763. { if (op->dilation_h != op->dilation_w) fprintf(pp, " 12=%d", op->dilation_h); }
  1764. fprintf_param_value(" 3=%d", stride_w)
  1765. { if (op->stride_h != op->stride_w) fprintf(pp, " 13=%d", op->stride_h); }
  1766. fprintf_param_value(" 4=%d", pad_left)
  1767. { if (op->pad_top != op->pad_left) fprintf(pp, " 14=%d", op->pad_top); }
  1768. { if (op->pad_right != op->pad_left) fprintf(pp, " 15=%d", op->pad_right); }
  1769. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 16=%d", op->pad_bottom); }
  1770. fprintf_param_value(" 18=%d", output_pad_right)
  1771. { if (op->output_pad_bottom != op->output_pad_right) fprintf(pp, " 19=%d", op->output_pad_bottom); }
  1772. fprintf_param_value(" 20=%d", output_w)
  1773. { if (op->output_h != op->output_w) fprintf(pp, " 21=%d", op->output_h); }
  1774. fprintf_param_value(" 5=%d", bias_term)
  1775. fprintf_param_value(" 6=%d", weight_data_size)
  1776. fprintf_param_value(" 7=%d", group)
  1777. fprintf_param_value(" 9=%d", activation_type)
  1778. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1779. fwrite_weight_tag_data(0, op->weight_data, bp);
  1780. fwrite_weight_data(op->bias_data, bp);
  1781. }
  1782. else if (layer->type == "DetectionOutput")
  1783. {
  1784. ncnn::DetectionOutput* op = (ncnn::DetectionOutput*)layer;
  1785. ncnn::DetectionOutput* op_default = (ncnn::DetectionOutput*)layer_default;
  1786. fprintf_param_value(" 0=%d", num_class)
  1787. fprintf_param_value(" 1=%e", nms_threshold)
  1788. fprintf_param_value(" 2=%d", nms_top_k)
  1789. fprintf_param_value(" 3=%d", keep_top_k)
  1790. fprintf_param_value(" 4=%e", confidence_threshold)
  1791. fprintf_param_value(" 5=%e", variances[0])
  1792. fprintf_param_value(" 6=%e", variances[1])
  1793. fprintf_param_value(" 7=%e", variances[2])
  1794. fprintf_param_value(" 8=%e", variances[3])
  1795. }
  1796. else if (layer->type == "Dropout")
  1797. {
  1798. ncnn::Dropout* op = (ncnn::Dropout*)layer;
  1799. ncnn::Dropout* op_default = (ncnn::Dropout*)layer_default;
  1800. fprintf_param_value(" 0=%e", scale)
  1801. }
  1802. else if (layer->type == "Eltwise")
  1803. {
  1804. ncnn::Eltwise* op = (ncnn::Eltwise*)layer;
  1805. ncnn::Eltwise* op_default = (ncnn::Eltwise*)layer_default;
  1806. fprintf_param_value(" 0=%d", op_type)
  1807. { if (!op->coeffs.empty()) fprintf_param_float_array(1, op->coeffs, pp); }
  1808. }
  1809. else if (layer->type == "ELU")
  1810. {
  1811. ncnn::ELU* op = (ncnn::ELU*)layer;
  1812. ncnn::ELU* op_default = (ncnn::ELU*)layer_default;
  1813. fprintf_param_value(" 0=%e", alpha)
  1814. }
  1815. else if (layer->type == "Exp")
  1816. {
  1817. ncnn::Exp* op = (ncnn::Exp*)layer;
  1818. ncnn::Exp* op_default = (ncnn::Exp*)layer_default;
  1819. fprintf_param_value(" 0=%e", base)
  1820. fprintf_param_value(" 1=%e", scale)
  1821. fprintf_param_value(" 2=%e", shift)
  1822. }
  1823. else if (layer->type == "ExpandDims")
  1824. {
  1825. ncnn::ExpandDims* op = (ncnn::ExpandDims*)layer;
  1826. ncnn::ExpandDims* op_default = (ncnn::ExpandDims*)layer_default;
  1827. fprintf_param_value(" 0=%d", expand_w)
  1828. fprintf_param_value(" 1=%d", expand_h)
  1829. fprintf_param_value(" 2=%d", expand_c)
  1830. { if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp); }
  1831. }
  1832. else if (layer->type == "HardSigmoid")
  1833. {
  1834. ncnn::HardSigmoid* op = (ncnn::HardSigmoid*)layer;
  1835. ncnn::HardSigmoid* op_default = (ncnn::HardSigmoid*)layer_default;
  1836. fprintf_param_value(" 0=%e", alpha)
  1837. fprintf_param_value(" 1=%e", beta)
  1838. }
  1839. else if (layer->type == "HardSwish")
  1840. {
  1841. ncnn::HardSwish* op = (ncnn::HardSwish*)layer;
  1842. ncnn::HardSwish* op_default = (ncnn::HardSwish*)layer_default;
  1843. fprintf_param_value(" 0=%e", alpha)
  1844. fprintf_param_value(" 1=%e", beta)
  1845. }
  1846. else if (layer->type == "InnerProduct")
  1847. {
  1848. ncnn::InnerProduct* op = (ncnn::InnerProduct*)layer;
  1849. ncnn::InnerProduct* op_default = (ncnn::InnerProduct*)layer_default;
  1850. fprintf_param_value(" 0=%d", num_output)
  1851. fprintf_param_value(" 1=%d", bias_term)
  1852. fprintf_param_value(" 2=%d", weight_data_size)
  1853. fprintf_param_value(" 8=%d", int8_scale_term)
  1854. fprintf_param_value(" 9=%d", activation_type)
  1855. { if (!op->activation_params.empty()) fprintf_param_float_array(10, op->activation_params, pp); }
  1856. fwrite_weight_tag_data(0, op->weight_data, bp);
  1857. fwrite_weight_data(op->bias_data, bp);
  1858. }
  1859. else if (layer->type == "Input")
  1860. {
  1861. ncnn::Input* op = (ncnn::Input*)layer;
  1862. ncnn::Input* op_default = (ncnn::Input*)layer_default;
  1863. fprintf_param_value(" 0=%d", w)
  1864. fprintf_param_value(" 1=%d", h)
  1865. fprintf_param_value(" 2=%d", c)
  1866. }
  1867. else if (layer->type == "InstanceNorm")
  1868. {
  1869. ncnn::InstanceNorm* op = (ncnn::InstanceNorm*)layer;
  1870. ncnn::InstanceNorm* op_default = (ncnn::InstanceNorm*)layer_default;
  1871. fprintf_param_value(" 0=%d", channels)
  1872. fprintf_param_value(" 1=%e", eps)
  1873. fwrite_weight_data(op->gamma_data, bp);
  1874. fwrite_weight_data(op->beta_data, bp);
  1875. }
  1876. else if (layer->type == "Interp")
  1877. {
  1878. ncnn::Interp* op = (ncnn::Interp*)layer;
  1879. ncnn::Interp* op_default = (ncnn::Interp*)layer_default;
  1880. fprintf_param_value(" 0=%d", resize_type)
  1881. fprintf_param_value(" 1=%e", height_scale)
  1882. fprintf_param_value(" 2=%e", width_scale)
  1883. fprintf_param_value(" 3=%d", output_height)
  1884. fprintf_param_value(" 4=%d", output_width)
  1885. }
  1886. else if (layer->type == "Log")
  1887. {
  1888. ncnn::Log* op = (ncnn::Log*)layer;
  1889. ncnn::Log* op_default = (ncnn::Log*)layer_default;
  1890. fprintf_param_value(" 0=%e", base)
  1891. fprintf_param_value(" 1=%e", scale)
  1892. fprintf_param_value(" 2=%e", shift)
  1893. }
  1894. else if (layer->type == "LRN")
  1895. {
  1896. ncnn::LRN* op = (ncnn::LRN*)layer;
  1897. ncnn::LRN* op_default = (ncnn::LRN*)layer_default;
  1898. fprintf_param_value(" 0=%d", region_type)
  1899. fprintf_param_value(" 1=%d", local_size)
  1900. fprintf_param_value(" 2=%e", alpha)
  1901. fprintf_param_value(" 3=%e", beta)
  1902. fprintf_param_value(" 4=%e", bias)
  1903. }
  1904. else if (layer->type == "MemoryData")
  1905. {
  1906. ncnn::MemoryData* op = (ncnn::MemoryData*)layer;
  1907. ncnn::MemoryData* op_default = (ncnn::MemoryData*)layer_default;
  1908. fprintf_param_value(" 0=%d", w)
  1909. fprintf_param_value(" 1=%d", h)
  1910. fprintf_param_value(" 2=%d", c)
  1911. fwrite_weight_data(op->data, bp);
  1912. }
  1913. else if (layer->type == "MVN")
  1914. {
  1915. ncnn::MVN* op = (ncnn::MVN*)layer;
  1916. ncnn::MVN* op_default = (ncnn::MVN*)layer_default;
  1917. fprintf_param_value(" 0=%d", normalize_variance)
  1918. fprintf_param_value(" 1=%d", across_channels)
  1919. fprintf_param_value(" 2=%e", eps)
  1920. }
  1921. else if (layer->type == "Normalize")
  1922. {
  1923. ncnn::Normalize* op = (ncnn::Normalize*)layer;
  1924. ncnn::Normalize* op_default = (ncnn::Normalize*)layer_default;
  1925. fprintf_param_value(" 0=%d", across_spatial)
  1926. fprintf_param_value(" 1=%d", channel_shared)
  1927. fprintf_param_value(" 2=%e", eps)
  1928. fprintf_param_value(" 3=%d", scale_data_size)
  1929. fprintf_param_value(" 4=%d", across_channel)
  1930. fprintf_param_value(" 9=%d", eps_mode)
  1931. fwrite_weight_data(op->scale_data, bp);
  1932. }
  1933. else if (layer->type == "Padding")
  1934. {
  1935. ncnn::Padding* op = (ncnn::Padding*)layer;
  1936. ncnn::Padding* op_default = (ncnn::Padding*)layer_default;
  1937. fprintf_param_value(" 0=%d", top)
  1938. fprintf_param_value(" 1=%d", bottom)
  1939. fprintf_param_value(" 2=%d", left)
  1940. fprintf_param_value(" 3=%d", right)
  1941. fprintf_param_value(" 4=%d", type)
  1942. fprintf_param_value(" 5=%e", value)
  1943. }
  1944. else if (layer->type == "Permute")
  1945. {
  1946. ncnn::Permute* op = (ncnn::Permute*)layer;
  1947. ncnn::Permute* op_default = (ncnn::Permute*)layer_default;
  1948. fprintf_param_value(" 0=%d", order_type)
  1949. }
  1950. else if (layer->type == "Pooling")
  1951. {
  1952. ncnn::Pooling* op = (ncnn::Pooling*)layer;
  1953. ncnn::Pooling* op_default = (ncnn::Pooling*)layer_default;
  1954. fprintf_param_value(" 0=%d", pooling_type)
  1955. fprintf_param_value(" 1=%d", kernel_w)
  1956. { if (op->kernel_h != op->kernel_w) fprintf(pp, " 11=%d", op->kernel_h); }
  1957. fprintf_param_value(" 2=%d", stride_w)
  1958. { if (op->stride_h != op->stride_w) fprintf(pp, " 12=%d", op->stride_h); }
  1959. fprintf_param_value(" 3=%d", pad_left)
  1960. { if (op->pad_top != op->pad_left) fprintf(pp, " 13=%d", op->pad_top); }
  1961. { if (op->pad_right != op->pad_left) fprintf(pp, " 14=%d", op->pad_right); }
  1962. { if (op->pad_bottom != op->pad_top) fprintf(pp, " 15=%d", op->pad_bottom); }
  1963. fprintf_param_value(" 4=%d", global_pooling)
  1964. fprintf_param_value(" 5=%d", pad_mode)
  1965. }
  1966. else if (layer->type == "Power")
  1967. {
  1968. ncnn::Power* op = (ncnn::Power*)layer;
  1969. ncnn::Power* op_default = (ncnn::Power*)layer_default;
  1970. fprintf_param_value(" 0=%e", power)
  1971. fprintf_param_value(" 1=%e", scale)
  1972. fprintf_param_value(" 2=%e", shift)
  1973. }
  1974. else if (layer->type == "PReLU")
  1975. {
  1976. ncnn::PReLU* op = (ncnn::PReLU*)layer;
  1977. ncnn::PReLU* op_default = (ncnn::PReLU*)layer_default;
  1978. fprintf_param_value(" 0=%d", num_slope)
  1979. fwrite_weight_data(op->slope_data, bp);
  1980. }
  1981. else if (layer->type == "PriorBox")
  1982. {
  1983. ncnn::PriorBox* op = (ncnn::PriorBox*)layer;
  1984. ncnn::PriorBox* op_default = (ncnn::PriorBox*)layer_default;
  1985. { if (!op->min_sizes.empty()) fprintf_param_float_array(0, op->min_sizes, pp); }
  1986. { if (!op->max_sizes.empty()) fprintf_param_float_array(1, op->max_sizes, pp); }
  1987. { if (!op->aspect_ratios.empty()) fprintf_param_float_array(2, op->aspect_ratios, pp); }
  1988. fprintf_param_value(" 3=%e", variances[0])
  1989. fprintf_param_value(" 4=%e", variances[1])
  1990. fprintf_param_value(" 5=%e", variances[2])
  1991. fprintf_param_value(" 6=%e", variances[3])
  1992. fprintf_param_value(" 7=%d", flip)
  1993. fprintf_param_value(" 8=%d", clip)
  1994. fprintf_param_value(" 9=%d", image_width)
  1995. fprintf_param_value(" 10=%d", image_height)
  1996. fprintf_param_value(" 11=%e", step_width)
  1997. fprintf_param_value(" 12=%e", step_height)
  1998. fprintf_param_value(" 13=%e", offset)
  1999. }
  2000. else if (layer->type == "Proposal")
  2001. {
  2002. ncnn::Proposal* op = (ncnn::Proposal*)layer;
  2003. ncnn::Proposal* op_default = (ncnn::Proposal*)layer_default;
  2004. fprintf_param_value(" 0=%d", feat_stride)
  2005. fprintf_param_value(" 1=%d", base_size)
  2006. fprintf_param_value(" 2=%d", pre_nms_topN)
  2007. fprintf_param_value(" 3=%d", after_nms_topN)
  2008. fprintf_param_value(" 4=%e", nms_thresh)
  2009. fprintf_param_value(" 5=%d", min_size)
  2010. }
  2011. else if (layer->type == "PSROIPooling")
  2012. {
  2013. ncnn::PSROIPooling* op = (ncnn::PSROIPooling*)layer;
  2014. ncnn::PSROIPooling* op_default = (ncnn::PSROIPooling*)layer_default;
  2015. fprintf_param_value(" 0=%d", pooled_width)
  2016. fprintf_param_value(" 1=%d", pooled_height)
  2017. fprintf_param_value(" 2=%e", spatial_scale)
  2018. fprintf_param_value(" 3=%d", output_dim)
  2019. }
  2020. else if (layer->type == "Quantize")
  2021. {
  2022. ncnn::Quantize* op = (ncnn::Quantize*)layer;
  2023. ncnn::Quantize* op_default = (ncnn::Quantize*)layer_default;
  2024. fprintf_param_value(" 0=%e", scale)
  2025. }
  2026. else if (layer->type == "Reduction")
  2027. {
  2028. ncnn::Reduction* op = (ncnn::Reduction*)layer;
  2029. ncnn::Reduction* op_default = (ncnn::Reduction*)layer_default;
  2030. fprintf_param_value(" 0=%d", operation)
  2031. fprintf_param_value(" 1=%d", reduce_all)
  2032. fprintf_param_value(" 2=%e", coeff)
  2033. { if (!op->axes.empty()) fprintf_param_int_array(3, op->axes, pp); }
  2034. fprintf_param_value(" 4=%d", keepdims)
  2035. }
  2036. else if (layer->type == "ReLU")
  2037. {
  2038. ncnn::ReLU* op = (ncnn::ReLU*)layer;
  2039. ncnn::ReLU* op_default = (ncnn::ReLU*)layer_default;
  2040. fprintf_param_value(" 0=%e", slope)
  2041. }
  2042. else if (layer->type == "Reorg")
  2043. {
  2044. ncnn::Reorg* op = (ncnn::Reorg*)layer;
  2045. ncnn::Reorg* op_default = (ncnn::Reorg*)layer_default;
  2046. fprintf_param_value(" 0=%d", stride)
  2047. }
  2048. else if (layer->type == "Requantize")
  2049. {
  2050. ncnn::Requantize* op = (ncnn::Requantize*)layer;
  2051. ncnn::Requantize* op_default = (ncnn::Requantize*)layer_default;
  2052. fprintf_param_value(" 0=%e", scale_in)
  2053. fprintf_param_value(" 1=%e", scale_out)
  2054. fprintf_param_value(" 2=%d", bias_term)
  2055. fprintf_param_value(" 3=%d", bias_data_size)
  2056. fprintf_param_value(" 4=%d", fusion_relu)
  2057. }
  2058. else if (layer->type == "Reshape")
  2059. {
  2060. ncnn::Reshape* op = (ncnn::Reshape*)layer;
  2061. ncnn::Reshape* op_default = (ncnn::Reshape*)layer_default;
  2062. fprintf_param_value(" 0=%d", w)
  2063. fprintf_param_value(" 1=%d", h)
  2064. fprintf_param_value(" 2=%d", c)
  2065. fprintf_param_value(" 3=%d", permute)
  2066. }
  2067. else if (layer->type == "ROIAlign")
  2068. {
  2069. ncnn::ROIAlign* op = (ncnn::ROIAlign*)layer;
  2070. ncnn::ROIAlign* op_default = (ncnn::ROIAlign*)layer_default;
  2071. fprintf_param_value(" 0=%d", pooled_width)
  2072. fprintf_param_value(" 1=%d", pooled_height)
  2073. fprintf_param_value(" 2=%e", spatial_scale)
  2074. }
  2075. else if (layer->type == "ROIPooling")
  2076. {
  2077. ncnn::ROIPooling* op = (ncnn::ROIPooling*)layer;
  2078. ncnn::ROIPooling* op_default = (ncnn::ROIPooling*)layer_default;
  2079. fprintf_param_value(" 0=%d", pooled_width)
  2080. fprintf_param_value(" 1=%d", pooled_height)
  2081. fprintf_param_value(" 2=%e", spatial_scale)
  2082. }
  2083. else if (layer->type == "Scale")
  2084. {
  2085. ncnn::Scale* op = (ncnn::Scale*)layer;
  2086. ncnn::Scale* op_default = (ncnn::Scale*)layer_default;
  2087. fprintf_param_value(" 0=%d", scale_data_size)
  2088. fprintf_param_value(" 1=%d", bias_term)
  2089. fwrite_weight_data(op->scale_data, bp);
  2090. fwrite_weight_data(op->bias_data, bp);
  2091. }
  2092. else if (layer->type == "ShuffleChannel")
  2093. {
  2094. ncnn::ShuffleChannel* op = (ncnn::ShuffleChannel*)layer;
  2095. ncnn::ShuffleChannel* op_default = (ncnn::ShuffleChannel*)layer_default;
  2096. fprintf_param_value(" 0=%d", group)
  2097. }
  2098. else if (layer->type == "Slice")
  2099. {
  2100. ncnn::Slice* op = (ncnn::Slice*)layer;
  2101. ncnn::Slice* op_default = (ncnn::Slice*)layer_default;
  2102. { if (!op->slices.empty()) fprintf_param_int_array(0, op->slices, pp); }
  2103. fprintf_param_value(" 1=%d", axis)
  2104. }
  2105. else if (layer->type == "Softmax")
  2106. {
  2107. ncnn::Softmax* op = (ncnn::Softmax*)layer;
  2108. ncnn::Softmax* op_default = (ncnn::Softmax*)layer_default;
  2109. fprintf_param_value(" 0=%d", axis)
  2110. // HACK
  2111. if (op->axis != 0)
  2112. {
  2113. int fixbug0 = 1;
  2114. fprintf(pp, " 1=%d", fixbug0);
  2115. }
  2116. }
  2117. else if (layer->type == "Squeeze")
  2118. {
  2119. ncnn::Squeeze* op = (ncnn::Squeeze*)layer;
  2120. ncnn::Squeeze* op_default = (ncnn::Squeeze*)layer_default;
  2121. fprintf_param_value(" 0=%d", squeeze_w)
  2122. fprintf_param_value(" 1=%d", squeeze_h)
  2123. fprintf_param_value(" 2=%d", squeeze_c)
  2124. { if (!op->axes.empty()) fprintf_param_int_array(0, op->axes, pp); }
  2125. }
  2126. else if (layer->type == "Threshold")
  2127. {
  2128. ncnn::Threshold* op = (ncnn::Threshold*)layer;
  2129. ncnn::Threshold* op_default = (ncnn::Threshold*)layer_default;
  2130. fprintf_param_value(" 0=%e", threshold)
  2131. }
  2132. else if (layer->type == "UnaryOp")
  2133. {
  2134. ncnn::UnaryOp* op = (ncnn::UnaryOp*)layer;
  2135. ncnn::UnaryOp* op_default = (ncnn::UnaryOp*)layer_default;
  2136. fprintf_param_value(" 0=%d", op_type)
  2137. }
  2138. else if (layer->type == "YoloDetectionOutput")
  2139. {
  2140. ncnn::YoloDetectionOutput* op = (ncnn::YoloDetectionOutput*)layer;
  2141. ncnn::YoloDetectionOutput* op_default = (ncnn::YoloDetectionOutput*)layer_default;
  2142. fprintf_param_value(" 0=%d", num_class)
  2143. fprintf_param_value(" 1=%d", num_box)
  2144. fprintf_param_value(" 2=%e", confidence_threshold)
  2145. fprintf_param_value(" 3=%e", nms_threshold)
  2146. { if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp); }
  2147. }
  2148. else if (layer->type == "Yolov3DetectionOutput")
  2149. {
  2150. ncnn::Yolov3DetectionOutput* op = (ncnn::Yolov3DetectionOutput*)layer;
  2151. ncnn::Yolov3DetectionOutput* op_default = (ncnn::Yolov3DetectionOutput*)layer_default;
  2152. fprintf_param_value(" 0=%d", num_class)
  2153. fprintf_param_value(" 1=%d", num_box)
  2154. fprintf_param_value(" 2=%e", confidence_threshold)
  2155. fprintf_param_value(" 3=%e", nms_threshold)
  2156. { if (!op->biases.empty()) fprintf_param_float_array(4, op->biases, pp); }
  2157. { if (!op->mask.empty()) fprintf_param_int_array(5, op->mask, pp); }
  2158. { if (!op->anchors_scale.empty()) fprintf_param_float_array(6, op->anchors_scale, pp); }
  2159. }
  2160. #undef fprintf_param_value
  2161. fprintf(pp, "\n");
  2162. delete layer_default;
  2163. }
  2164. fclose(pp);
  2165. fclose(bp);
  2166. return 0;
  2167. }
  2168. int main(int argc, char** argv)
  2169. {
  2170. #if defined(__aarch64__) && defined(LINUX)
  2171. if (argc != 10)
  2172. {
  2173. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag] [dataname] [w] [h] [c]\n", argv[0]);
  2174. return -1;
  2175. }
  2176. const char* dataname = argv[6];
  2177. int inw = atoi(argv[7]);
  2178. int inh = atoi(argv[8]);
  2179. int inc = atoi(argv[9]);
  2180. #else
  2181. if (argc != 6)
  2182. {
  2183. fprintf(stderr, "usage: %s [inparam] [inbin] [outparam] [outbin] [flag]\n", argv[0]);
  2184. return -1;
  2185. }
  2186. #endif // defined(__aarch64__) && defined(LINUX)
  2187. const char* inparam = argv[1];
  2188. const char* inbin = argv[2];
  2189. const char* outparam = argv[3];
  2190. const char* outbin = argv[4];
  2191. int flag = atoi(argv[5]);
  2192. NetOptimize optimizer;
  2193. if (flag == 65536)
  2194. {
  2195. optimizer.storage_type = 1;
  2196. }
  2197. else
  2198. {
  2199. optimizer.storage_type = 0;
  2200. }
  2201. optimizer.load_param(inparam);
  2202. if (strcmp(inbin, "null") == 0)
  2203. {
  2204. DataReaderFromEmpty dr;
  2205. optimizer.load_model(dr);
  2206. }
  2207. else
  2208. optimizer.load_model(inbin);
  2209. #if defined(__aarch64__) && defined(LINUX)
  2210. optimizer.find_fastest_fp32_conv(dataname, inw, inh, inc);
  2211. #endif // defined(__aarch64__) && defined(LINUX)
  2212. optimizer.fuse_batchnorm_scale();
  2213. optimizer.fuse_convolution_batchnorm();
  2214. optimizer.fuse_convolutiondepthwise_batchnorm();
  2215. optimizer.fuse_deconvolution_batchnorm();
  2216. optimizer.fuse_deconvolutiondepthwise_batchnorm();
  2217. optimizer.fuse_innerproduct_batchnorm();
  2218. optimizer.fuse_innerproduct_dropout();
  2219. optimizer.fuse_convolution_activation();
  2220. optimizer.fuse_convolutiondepthwise_activation();
  2221. optimizer.fuse_deconvolution_activation();
  2222. optimizer.fuse_deconvolutiondepthwise_activation();
  2223. optimizer.fuse_innerproduct_activation();
  2224. optimizer.eliminate_dropout();
  2225. optimizer.eliminate_pooling1x1();
  2226. optimizer.eliminate_noop();
  2227. optimizer.eliminate_flatten_after_global_pooling();
  2228. optimizer.eliminate_reshape_after_global_pooling();
  2229. optimizer.eliminate_reshape_before_binaryop();
  2230. optimizer.replace_convolution_with_innerproduct_after_global_pooling();
  2231. optimizer.replace_convolution_with_innerproduct_after_innerproduct();
  2232. optimizer.eliminate_flatten_after_innerproduct();
  2233. optimizer.eliminate_orphaned_memorydata();
  2234. optimizer.shape_inference();
  2235. optimizer.save(outparam, outbin);
  2236. return 0;
  2237. }