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