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