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.

caffe2ncnn.cpp 64 kB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include <stdio.h>
  15. #include <limits.h>
  16. #include <math.h>
  17. #include <fstream>
  18. #include <set>
  19. #include <limits>
  20. #include <map>
  21. #include <algorithm>
  22. #include <google/protobuf/io/coded_stream.h>
  23. #include <google/protobuf/io/zero_copy_stream_impl.h>
  24. #include <google/protobuf/text_format.h>
  25. #include <google/protobuf/message.h>
  26. #include "caffe.pb.h"
  27. static inline size_t alignSize(size_t sz, int n)
  28. {
  29. return (sz + n-1) & -n;
  30. }
  31. // convert float to half precision floating point
  32. static unsigned short float2half(float value)
  33. {
  34. // 1 : 8 : 23
  35. union
  36. {
  37. unsigned int u;
  38. float f;
  39. } tmp;
  40. tmp.f = value;
  41. // 1 : 8 : 23
  42. unsigned short sign = (tmp.u & 0x80000000) >> 31;
  43. unsigned short exponent = (tmp.u & 0x7F800000) >> 23;
  44. unsigned int significand = tmp.u & 0x7FFFFF;
  45. // fprintf(stderr, "%d %d %d\n", sign, exponent, significand);
  46. // 1 : 5 : 10
  47. unsigned short fp16;
  48. if (exponent == 0)
  49. {
  50. // zero or denormal, always underflow
  51. fp16 = (sign << 15) | (0x00 << 10) | 0x00;
  52. }
  53. else if (exponent == 0xFF)
  54. {
  55. // infinity or NaN
  56. fp16 = (sign << 15) | (0x1F << 10) | (significand ? 0x200 : 0x00);
  57. }
  58. else
  59. {
  60. // normalized
  61. short newexp = exponent + (- 127 + 15);
  62. if (newexp >= 31)
  63. {
  64. // overflow, return infinity
  65. fp16 = (sign << 15) | (0x1F << 10) | 0x00;
  66. }
  67. else if (newexp <= 0)
  68. {
  69. // underflow
  70. if (newexp >= -10)
  71. {
  72. // denormal half-precision
  73. unsigned short sig = (significand | 0x800000) >> (14 - newexp);
  74. fp16 = (sign << 15) | (0x00 << 10) | sig;
  75. }
  76. else
  77. {
  78. // underflow
  79. fp16 = (sign << 15) | (0x00 << 10) | 0x00;
  80. }
  81. }
  82. else
  83. {
  84. fp16 = (sign << 15) | (newexp << 10) | (significand >> 13);
  85. }
  86. }
  87. return fp16;
  88. }
  89. // round to nearest
  90. static signed char float2int8(float value)
  91. {
  92. float tmp;
  93. if (value >= 0.f) tmp = value + 0.5;
  94. else tmp = value - 0.5;
  95. if (tmp > 127)
  96. return 127;
  97. if (tmp < -128)
  98. return -128;
  99. return tmp;
  100. }
  101. static bool read_int8scale_table(const char* filepath, std::map<std::string, std::vector<float> >& blob_int8scale_table, std::map<std::string, std::vector<float> >& weight_int8scale_table)
  102. {
  103. blob_int8scale_table.clear();
  104. weight_int8scale_table.clear();
  105. FILE* fp = fopen(filepath, "rb");
  106. if (!fp)
  107. {
  108. fprintf(stderr, "fopen %s failed\n", filepath);
  109. return false;
  110. }
  111. bool in_scale_vector = false;
  112. std::string keystr;
  113. std::vector<float> scales;
  114. while (!feof(fp))
  115. {
  116. char key[256];
  117. int nscan = fscanf(fp, "%255s", key);
  118. if (nscan != 1)
  119. {
  120. break;
  121. }
  122. if (in_scale_vector)
  123. {
  124. float scale = 1.f;
  125. int nscan = sscanf(key, "%f", &scale);
  126. if (nscan == 1)
  127. {
  128. scales.push_back(scale);
  129. continue;
  130. }
  131. else
  132. {
  133. // XYZ_param_N pattern
  134. if (strstr(keystr.c_str(), "_param_"))
  135. {
  136. weight_int8scale_table[ keystr ] = scales;
  137. }
  138. else
  139. {
  140. blob_int8scale_table[ keystr ] = scales;
  141. }
  142. keystr.clear();
  143. scales.clear();
  144. in_scale_vector = false;
  145. }
  146. }
  147. if (!in_scale_vector)
  148. {
  149. keystr = key;
  150. in_scale_vector = true;
  151. }
  152. }
  153. if (in_scale_vector)
  154. {
  155. // XYZ_param_N pattern
  156. if (strstr(keystr.c_str(), "_param_"))
  157. {
  158. weight_int8scale_table[ keystr ] = scales;
  159. }
  160. else
  161. {
  162. blob_int8scale_table[ keystr ] = scales;
  163. }
  164. }
  165. fclose(fp);
  166. return true;
  167. }
  168. static int quantize_weight(float *data, size_t data_length, std::vector<unsigned short>& float16_weights)
  169. {
  170. float16_weights.resize(data_length);
  171. for (size_t i = 0; i < data_length; i++)
  172. {
  173. float f = data[i];
  174. unsigned short fp16 = float2half(f);
  175. float16_weights[i] = fp16;
  176. }
  177. // magic tag for half-precision floating point
  178. return 0x01306B47;
  179. }
  180. static int quantize_weight(float *data, size_t data_length, std::vector<float> scales, std::vector<signed char>& int8_weights)
  181. {
  182. int8_weights.resize(data_length);
  183. int length_per_group = data_length / scales.size();
  184. for (size_t i = 0; i < data_length; i++)
  185. {
  186. float f = data[i];
  187. signed char int8 = float2int8(f * scales[ i / length_per_group ]);
  188. int8_weights[i] = int8;
  189. }
  190. // magic tag for int8
  191. return 0x000D4B38;
  192. }
  193. static bool quantize_weight(float *data, size_t data_length, int quantize_level, std::vector<float> &quantize_table, std::vector<unsigned char> &quantize_index) {
  194. assert(quantize_level != 0);
  195. assert(data != NULL);
  196. assert(data_length > 0);
  197. if (data_length < static_cast<size_t>(quantize_level)) {
  198. fprintf(stderr, "No need quantize,because: data_length < quantize_level");
  199. return false;
  200. }
  201. quantize_table.reserve(quantize_level);
  202. quantize_index.reserve(data_length);
  203. // 1. Find min and max value
  204. float max_value = std::numeric_limits<float>::min();
  205. float min_value = std::numeric_limits<float>::max();
  206. for (size_t i = 0; i < data_length; ++i)
  207. {
  208. if (max_value < data[i]) max_value = data[i];
  209. if (min_value > data[i]) min_value = data[i];
  210. }
  211. float strides = (max_value - min_value) / quantize_level;
  212. // 2. Generate quantize table
  213. for (int i = 0; i < quantize_level; ++i)
  214. {
  215. quantize_table.push_back(min_value + i * strides);
  216. }
  217. // 3. Align data to the quantized value
  218. for (size_t i = 0; i < data_length; ++i)
  219. {
  220. size_t table_index = int((data[i] - min_value) / strides);
  221. table_index = std::min<float>(table_index, quantize_level - 1);
  222. float low_value = quantize_table[table_index];
  223. float high_value = low_value + strides;
  224. // find a nearest value between low and high value.
  225. float targetValue = data[i] - low_value < high_value - data[i] ? low_value : high_value;
  226. table_index = int((targetValue - min_value) / strides);
  227. table_index = std::min<float>(table_index, quantize_level - 1);
  228. quantize_index.push_back(table_index);
  229. }
  230. return true;
  231. }
  232. static bool read_proto_from_text(const char* filepath, google::protobuf::Message* message)
  233. {
  234. std::ifstream fs(filepath, std::ifstream::in);
  235. if (!fs.is_open())
  236. {
  237. fprintf(stderr, "open failed %s\n", filepath);
  238. return false;
  239. }
  240. google::protobuf::io::IstreamInputStream input(&fs);
  241. bool success = google::protobuf::TextFormat::Parse(&input, message);
  242. fs.close();
  243. return success;
  244. }
  245. static bool read_proto_from_binary(const char* filepath, google::protobuf::Message* message)
  246. {
  247. std::ifstream fs(filepath, std::ifstream::in | std::ifstream::binary);
  248. if (!fs.is_open())
  249. {
  250. fprintf(stderr, "open failed %s\n", filepath);
  251. return false;
  252. }
  253. google::protobuf::io::IstreamInputStream input(&fs);
  254. google::protobuf::io::CodedInputStream codedstr(&input);
  255. codedstr.SetTotalBytesLimit(INT_MAX, INT_MAX / 2);
  256. bool success = message->ParseFromCodedStream(&codedstr);
  257. fs.close();
  258. return success;
  259. }
  260. int main(int argc, char** argv)
  261. {
  262. if (!(argc == 3 || argc == 5 || argc == 6 || argc == 7))
  263. {
  264. fprintf(stderr, "Usage: %s [caffeproto] [caffemodel] [ncnnproto] [ncnnbin] [quantizelevel] [int8scaletable]\n", argv[0]);
  265. return -1;
  266. }
  267. const char* caffeproto = argv[1];
  268. const char* caffemodel = argv[2];
  269. const char* ncnn_prototxt = argc >= 5 ? argv[3] : "ncnn.proto";
  270. const char* ncnn_modelbin = argc >= 5 ? argv[4] : "ncnn.bin";
  271. const char* quantize_param = argc >= 6 ? argv[5] : "0";
  272. const char* int8scale_table_path = argc == 7 ? argv[6] : NULL;
  273. int quantize_level = atoi(quantize_param);
  274. if (quantize_level != 0 && quantize_level != 256 && quantize_level != 65536) {
  275. fprintf(stderr, "%s: only support quantize level = 0, 256, or 65536", argv[0]);
  276. return -1;
  277. }
  278. caffe::NetParameter proto;
  279. caffe::NetParameter net;
  280. // load
  281. bool s0 = read_proto_from_text(caffeproto, &proto);
  282. if (!s0)
  283. {
  284. fprintf(stderr, "read_proto_from_text failed\n");
  285. return -1;
  286. }
  287. bool s1 = read_proto_from_binary(caffemodel, &net);
  288. if (!s1)
  289. {
  290. fprintf(stderr, "read_proto_from_binary failed\n");
  291. return -1;
  292. }
  293. std::map<std::string, std::vector<float> > blob_int8scale_table;
  294. std::map<std::string, std::vector<float> > weight_int8scale_table;
  295. if (int8scale_table_path)
  296. {
  297. bool s2 = read_int8scale_table(int8scale_table_path, blob_int8scale_table, weight_int8scale_table);
  298. if (!s2)
  299. {
  300. fprintf(stderr, "read_int8scale_table failed\n");
  301. return -1;
  302. }
  303. }
  304. FILE* pp = fopen(ncnn_prototxt, "wb");
  305. FILE* bp = fopen(ncnn_modelbin, "wb");
  306. // magic
  307. fprintf(pp, "7767517\n");
  308. // rename mapping for identical bottom top style
  309. std::map<std::string, std::string> blob_name_decorated;
  310. // bottom blob reference
  311. std::map<std::string, int> bottom_reference;
  312. // global definition line
  313. // [layer count] [blob count]
  314. int layer_count = proto.layer_size();
  315. std::set<std::string> blob_names;
  316. for (int i=0; i<layer_count; i++)
  317. {
  318. const caffe::LayerParameter& layer = proto.layer(i);
  319. for (int j=0; j<layer.bottom_size(); j++)
  320. {
  321. std::string blob_name = layer.bottom(j);
  322. if (blob_name_decorated.find(blob_name) != blob_name_decorated.end())
  323. {
  324. blob_name = blob_name_decorated[blob_name];
  325. }
  326. blob_names.insert(blob_name);
  327. if (bottom_reference.find(blob_name) == bottom_reference.end())
  328. {
  329. bottom_reference[blob_name] = 1;
  330. }
  331. else
  332. {
  333. bottom_reference[blob_name] = bottom_reference[blob_name] + 1;
  334. }
  335. }
  336. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  337. {
  338. std::string blob_name = layer.top(0) + "_" + layer.name();
  339. blob_name_decorated[layer.top(0)] = blob_name;
  340. blob_names.insert(blob_name);
  341. }
  342. else
  343. {
  344. for (int j=0; j<layer.top_size(); j++)
  345. {
  346. std::string blob_name = layer.top(j);
  347. blob_names.insert(blob_name);
  348. }
  349. }
  350. }
  351. // remove bottom_reference entry with reference equals to one
  352. int splitncnn_blob_count = 0;
  353. std::map<std::string, int>::iterator it = bottom_reference.begin();
  354. while (it != bottom_reference.end())
  355. {
  356. if (it->second == 1)
  357. {
  358. bottom_reference.erase(it++);
  359. }
  360. else
  361. {
  362. splitncnn_blob_count += it->second;
  363. // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second);
  364. ++it;
  365. }
  366. }
  367. fprintf(pp, "%lu %lu\n", layer_count + bottom_reference.size(), blob_names.size() + splitncnn_blob_count);
  368. // populate
  369. blob_name_decorated.clear();
  370. int internal_split = 0;
  371. for (int i=0; i<layer_count; i++)
  372. {
  373. const caffe::LayerParameter& layer = proto.layer(i);
  374. // layer definition line, repeated
  375. // [type] [name] [bottom blob count] [top blob count] [bottom blobs] [top blobs] [layer specific params]
  376. if (layer.type() == "BN")
  377. {
  378. fprintf(pp, "%-16s", "Scale");
  379. }
  380. else if (layer.type() == "Convolution")
  381. {
  382. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  383. if (convolution_param.group() != 1)
  384. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  385. else
  386. fprintf(pp, "%-16s", "Convolution");
  387. }
  388. else if (layer.type() == "ConvolutionDepthwise" || layer.type() == "DepthwiseConvolution")
  389. {
  390. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  391. }
  392. else if (layer.type() == "Deconvolution")
  393. {
  394. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  395. if (convolution_param.group() != 1)
  396. fprintf(pp, "%-16s", "DeconvolutionDepthWise");
  397. else
  398. fprintf(pp, "%-16s", "Deconvolution");
  399. }
  400. else if (layer.type() == "MemoryData")
  401. {
  402. fprintf(pp, "%-16s", "Input");
  403. }
  404. else if (layer.type() == "Python")
  405. {
  406. const caffe::PythonParameter& python_param = layer.python_param();
  407. std::string python_layer_name = python_param.layer();
  408. if (python_layer_name == "ProposalLayer")
  409. fprintf(pp, "%-16s", "Proposal");
  410. else
  411. fprintf(pp, "%-16s", python_layer_name.c_str());
  412. }
  413. else if (layer.type() == "ReLU6")
  414. {
  415. fprintf(pp, "%-16s", "Clip");
  416. }
  417. else
  418. {
  419. fprintf(pp, "%-16s", layer.type().c_str());
  420. }
  421. fprintf(pp, " %-16s %d %d", layer.name().c_str(), layer.bottom_size(), layer.top_size());
  422. for (int j=0; j<layer.bottom_size(); j++)
  423. {
  424. std::string blob_name = layer.bottom(j);
  425. if (blob_name_decorated.find(layer.bottom(j)) != blob_name_decorated.end())
  426. {
  427. blob_name = blob_name_decorated[layer.bottom(j)];
  428. }
  429. if (bottom_reference.find(blob_name) != bottom_reference.end())
  430. {
  431. int refidx = bottom_reference[blob_name] - 1;
  432. bottom_reference[blob_name] = refidx;
  433. char splitsuffix[256];
  434. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  435. blob_name = blob_name + splitsuffix;
  436. }
  437. fprintf(pp, " %s", blob_name.c_str());
  438. }
  439. // decorated
  440. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  441. {
  442. std::string blob_name = layer.top(0) + "_" + layer.name();
  443. blob_name_decorated[layer.top(0)] = blob_name;
  444. fprintf(pp, " %s", blob_name.c_str());
  445. }
  446. else
  447. {
  448. for (int j=0; j<layer.top_size(); j++)
  449. {
  450. std::string blob_name = layer.top(j);
  451. fprintf(pp, " %s", blob_name.c_str());
  452. }
  453. }
  454. // find blob binary by layer name
  455. int netidx;
  456. for (netidx=0; netidx<net.layer_size(); netidx++)
  457. {
  458. if (net.layer(netidx).name() == layer.name())
  459. {
  460. break;
  461. }
  462. }
  463. // layer specific params
  464. if (layer.type() == "BatchNorm")
  465. {
  466. const caffe::LayerParameter& binlayer = net.layer(netidx);
  467. const caffe::BlobProto& mean_blob = binlayer.blobs(0);
  468. const caffe::BlobProto& var_blob = binlayer.blobs(1);
  469. fprintf(pp, " 0=%d", (int)mean_blob.data_size());
  470. const caffe::BatchNormParameter& batch_norm_param = layer.batch_norm_param();
  471. float eps = batch_norm_param.eps();
  472. std::vector<float> ones(mean_blob.data_size(), 1.f);
  473. fwrite(ones.data(), sizeof(float), ones.size(), bp);// slope
  474. if (binlayer.blobs_size() < 3)
  475. {
  476. fwrite(mean_blob.data().data(), sizeof(float), mean_blob.data_size(), bp);
  477. float tmp;
  478. for (int j=0; j<var_blob.data_size(); j++)
  479. {
  480. tmp = var_blob.data().data()[j] + eps;
  481. fwrite(&tmp, sizeof(float), 1, bp);
  482. }
  483. }
  484. else
  485. {
  486. float scale_factor = binlayer.blobs(2).data().data()[0] == 0 ? 0 : 1 / binlayer.blobs(2).data().data()[0];
  487. // premultiply scale_factor to mean and variance
  488. float tmp;
  489. for (int j=0; j<mean_blob.data_size(); j++)
  490. {
  491. tmp = mean_blob.data().data()[j] * scale_factor;
  492. fwrite(&tmp, sizeof(float), 1, bp);
  493. }
  494. for (int j=0; j<var_blob.data_size(); j++)
  495. {
  496. tmp = var_blob.data().data()[j] * scale_factor + eps;
  497. fwrite(&tmp, sizeof(float), 1, bp);
  498. }
  499. }
  500. std::vector<float> zeros(mean_blob.data_size(), 0.f);
  501. fwrite(zeros.data(), sizeof(float), zeros.size(), bp);// bias
  502. }
  503. else if (layer.type() == "BN")
  504. {
  505. const caffe::LayerParameter& binlayer = net.layer(netidx);
  506. const caffe::BlobProto& scale_blob = binlayer.blobs(0);
  507. const caffe::BlobProto& shift_blob = binlayer.blobs(1);
  508. fprintf(pp, " 0=%d", (int)scale_blob.data_size());
  509. fprintf(pp, " 1=1");
  510. fwrite(scale_blob.data().data(), sizeof(float), scale_blob.data_size(), bp);
  511. fwrite(shift_blob.data().data(), sizeof(float), shift_blob.data_size(), bp);
  512. }
  513. else if (layer.type() == "Concat")
  514. {
  515. const caffe::ConcatParameter& concat_param = layer.concat_param();
  516. int dim = concat_param.axis() - 1;
  517. fprintf(pp, " 0=%d", dim);
  518. }
  519. else if (layer.type() == "Convolution" || layer.type() == "ConvolutionDepthwise" || layer.type() == "DepthwiseConvolution")
  520. {
  521. const caffe::LayerParameter& binlayer = net.layer(netidx);
  522. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  523. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  524. fprintf(pp, " 0=%d", convolution_param.num_output());
  525. if (convolution_param.has_kernel_w() && convolution_param.has_kernel_h())
  526. {
  527. fprintf(pp, " 1=%d", convolution_param.kernel_w());
  528. fprintf(pp, " 11=%d", convolution_param.kernel_h());
  529. }
  530. else
  531. {
  532. fprintf(pp, " 1=%d", convolution_param.kernel_size(0));
  533. }
  534. fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1);
  535. if (convolution_param.has_stride_w() && convolution_param.has_stride_h())
  536. {
  537. fprintf(pp, " 3=%d", convolution_param.stride_w());
  538. fprintf(pp, " 13=%d", convolution_param.stride_h());
  539. }
  540. else
  541. {
  542. fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1);
  543. }
  544. if (convolution_param.has_pad_w() && convolution_param.has_pad_h())
  545. {
  546. fprintf(pp, " 4=%d", convolution_param.pad_w());
  547. fprintf(pp, " 14=%d", convolution_param.pad_h());
  548. }
  549. else
  550. {
  551. fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0);
  552. }
  553. fprintf(pp, " 5=%d", convolution_param.bias_term());
  554. fprintf(pp, " 6=%d", weight_blob.data_size());
  555. int num_group = 1;
  556. if (layer.type() == "ConvolutionDepthwise" || layer.type() == "DepthwiseConvolution")
  557. {
  558. num_group = convolution_param.num_output();
  559. }
  560. else
  561. {
  562. num_group = convolution_param.group();
  563. }
  564. if (num_group != 1)
  565. {
  566. fprintf(pp, " 7=%d", num_group);
  567. }
  568. bool int8_scale_term = false;
  569. std::vector<float> weight_int8scale;
  570. std::vector<float> blob_int8scale;
  571. if (int8scale_table_path)
  572. {
  573. char key[256];
  574. sprintf(key, "%s_param_0", layer.name().c_str());
  575. if (weight_int8scale_table.find(std::string(key)) != weight_int8scale_table.end())
  576. {
  577. weight_int8scale = weight_int8scale_table[std::string(key)];
  578. }
  579. if (blob_int8scale_table.find(layer.name()) != blob_int8scale_table.end())
  580. {
  581. blob_int8scale = blob_int8scale_table[layer.name()];
  582. }
  583. int8_scale_term = !weight_int8scale.empty() && !blob_int8scale.empty();
  584. if (int8_scale_term)
  585. {
  586. if ((int)weight_int8scale.size() == num_group)
  587. {
  588. fprintf(pp, " 8=1");
  589. }
  590. else
  591. {
  592. fprintf(pp, " 8=2");
  593. }
  594. }
  595. }
  596. for (int j = 0; j < binlayer.blobs_size(); j++)
  597. {
  598. int quantize_tag = 0;
  599. const caffe::BlobProto& blob = binlayer.blobs(j);
  600. std::vector<float> quantize_table;
  601. std::vector<unsigned char> quantize_index;
  602. std::vector<unsigned short> float16_weights;
  603. std::vector<signed char> int8_weights;
  604. // we will not quantize the bias values
  605. if (j == 0)
  606. {
  607. if (int8_scale_term)
  608. {
  609. if (quantize_level == 0)
  610. {
  611. quantize_tag = 0x0002C056;
  612. }
  613. else if (quantize_level == 256)
  614. {
  615. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), weight_int8scale, int8_weights);
  616. }
  617. }
  618. else if (quantize_level == 256)
  619. {
  620. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  621. }
  622. else if (quantize_level == 65536)
  623. {
  624. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  625. }
  626. // write quantize tag first
  627. fwrite(&quantize_tag, sizeof(int), 1, bp);
  628. if (quantize_tag)
  629. {
  630. int p0 = ftell(bp);
  631. if (int8_scale_term)
  632. {
  633. if (quantize_level == 0)
  634. {
  635. // write original data and int8scale
  636. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  637. }
  638. else if (quantize_level == 256)
  639. {
  640. fwrite(int8_weights.data(), sizeof(signed char), int8_weights.size(), bp);
  641. }
  642. }
  643. else if (quantize_level == 256)
  644. {
  645. // write quantize table and index
  646. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  647. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  648. }
  649. else if (quantize_level == 65536)
  650. {
  651. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  652. }
  653. // padding to 32bit align
  654. int nwrite = ftell(bp) - p0;
  655. int nalign = alignSize(nwrite, 4);
  656. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  657. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  658. }
  659. else
  660. {
  661. // write original data
  662. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  663. }
  664. }
  665. else
  666. {
  667. // write original data
  668. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  669. }
  670. }
  671. if (int8_scale_term)
  672. {
  673. // write int8_scale data
  674. fwrite(weight_int8scale.data(), sizeof(float), weight_int8scale.size(), bp);
  675. fwrite(blob_int8scale.data(), sizeof(float), blob_int8scale.size(), bp);
  676. }
  677. }
  678. else if (layer.type() == "Crop")
  679. {
  680. const caffe::CropParameter& crop_param = layer.crop_param();
  681. int num_offset = crop_param.offset_size();
  682. if (num_offset == 1)
  683. {
  684. int offset = crop_param.offset(0);
  685. int axis = crop_param.axis();
  686. if (axis == 1)
  687. {
  688. fprintf(pp, " 0=%d", offset);
  689. fprintf(pp, " 1=%d", offset);
  690. fprintf(pp, " 2=%d", offset);
  691. }
  692. else if (axis == 2)
  693. {
  694. fprintf(pp, " 0=%d", offset);
  695. fprintf(pp, " 1=%d", offset);
  696. }
  697. else if (axis == 3)
  698. {
  699. fprintf(pp, " 0=%d", offset);
  700. }
  701. }
  702. else if (num_offset == 2)
  703. {
  704. int woffset = crop_param.offset(1);
  705. int hoffset = crop_param.offset(0);
  706. fprintf(pp, " 0=%d", woffset);
  707. fprintf(pp, " 1=%d", hoffset);
  708. }
  709. else if (num_offset == 3)
  710. {
  711. int woffset = crop_param.offset(2);
  712. int hoffset = crop_param.offset(1);
  713. int coffset = crop_param.offset(0);
  714. fprintf(pp, " 0=%d", woffset);
  715. fprintf(pp, " 1=%d", hoffset);
  716. fprintf(pp, " 2=%d", coffset);
  717. }
  718. }
  719. else if (layer.type() == "Deconvolution")
  720. {
  721. const caffe::LayerParameter& binlayer = net.layer(netidx);
  722. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  723. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  724. fprintf(pp, " 0=%d", convolution_param.num_output());
  725. if (convolution_param.has_kernel_w() && convolution_param.has_kernel_h())
  726. {
  727. fprintf(pp, " 1=%d", convolution_param.kernel_w());
  728. fprintf(pp, " 11=%d", convolution_param.kernel_h());
  729. }
  730. else
  731. {
  732. fprintf(pp, " 1=%d", convolution_param.kernel_size(0));
  733. }
  734. fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1);
  735. if (convolution_param.has_stride_w() && convolution_param.has_stride_h())
  736. {
  737. fprintf(pp, " 3=%d", convolution_param.stride_w());
  738. fprintf(pp, " 13=%d", convolution_param.stride_h());
  739. }
  740. else
  741. {
  742. fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1);
  743. }
  744. if (convolution_param.has_pad_w() && convolution_param.has_pad_h())
  745. {
  746. fprintf(pp, " 4=%d", convolution_param.pad_w());
  747. fprintf(pp, " 14=%d", convolution_param.pad_h());
  748. }
  749. else
  750. {
  751. fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0);
  752. }
  753. fprintf(pp, " 5=%d", convolution_param.bias_term());
  754. fprintf(pp, " 6=%d", weight_blob.data_size());
  755. int group = convolution_param.group();
  756. if (group != 1)
  757. {
  758. fprintf(pp, " 7=%d", group);
  759. }
  760. int quantized_weight = 0;
  761. fwrite(&quantized_weight, sizeof(int), 1, bp);
  762. int maxk = 0;
  763. if (convolution_param.has_kernel_w() && convolution_param.has_kernel_h())
  764. {
  765. maxk = convolution_param.kernel_w() * convolution_param.kernel_h();
  766. }
  767. else
  768. {
  769. maxk = convolution_param.kernel_size(0) * convolution_param.kernel_size(0);
  770. }
  771. for (int g=0; g<group; g++)
  772. {
  773. // reorder weight from inch-outch to outch-inch
  774. int num_output = convolution_param.num_output() / group;
  775. int num_input = weight_blob.data_size() / maxk / num_output / group;
  776. const float* weight_data_ptr = weight_blob.data().data() + g * maxk * num_output * num_input;
  777. for (int k=0; k<num_output; k++)
  778. {
  779. for (int j=0; j<num_input; j++)
  780. {
  781. fwrite(weight_data_ptr + (j*num_output + k) * maxk, sizeof(float), maxk, bp);
  782. }
  783. }
  784. }
  785. for (int j=1; j<binlayer.blobs_size(); j++)
  786. {
  787. const caffe::BlobProto& blob = binlayer.blobs(j);
  788. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  789. }
  790. }
  791. else if (layer.type() == "DetectionOutput")
  792. {
  793. const caffe::DetectionOutputParameter& detection_output_param = layer.detection_output_param();
  794. const caffe::NonMaximumSuppressionParameter& nms_param = detection_output_param.nms_param();
  795. fprintf(pp, " 0=%d", detection_output_param.num_classes());
  796. fprintf(pp, " 1=%f", nms_param.nms_threshold());
  797. fprintf(pp, " 2=%d", nms_param.top_k());
  798. fprintf(pp, " 3=%d", detection_output_param.keep_top_k());
  799. fprintf(pp, " 4=%f", detection_output_param.confidence_threshold());
  800. }
  801. else if (layer.type() == "Dropout")
  802. {
  803. const caffe::DropoutParameter& dropout_param = layer.dropout_param();
  804. if (dropout_param.has_scale_train() && !dropout_param.scale_train())
  805. {
  806. float scale = 1.f - dropout_param.dropout_ratio();
  807. fprintf(pp, " 0=%f", scale);
  808. }
  809. }
  810. else if (layer.type() == "Eltwise")
  811. {
  812. const caffe::EltwiseParameter& eltwise_param = layer.eltwise_param();
  813. int coeff_size = eltwise_param.coeff_size();
  814. fprintf(pp, " 0=%d", (int)eltwise_param.operation());
  815. fprintf(pp, " -23301=%d", coeff_size);
  816. for (int j=0; j<coeff_size; j++)
  817. {
  818. fprintf(pp, ",%f", eltwise_param.coeff(j));
  819. }
  820. }
  821. else if (layer.type() == "ELU")
  822. {
  823. const caffe::ELUParameter& elu_param = layer.elu_param();
  824. fprintf(pp, " 0=%f", elu_param.alpha());
  825. }
  826. else if (layer.type() == "Embed")
  827. {
  828. const caffe::LayerParameter& binlayer = net.layer(netidx);
  829. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  830. const caffe::EmbedParameter& embed_param = layer.embed_param();
  831. fprintf(pp, " 0=%d", embed_param.num_output());
  832. fprintf(pp, " 1=%d", embed_param.input_dim());
  833. fprintf(pp, " 2=%d", embed_param.bias_term());
  834. fprintf(pp, " 3=%d", weight_blob.data_size());
  835. for (int j=0; j<binlayer.blobs_size(); j++)
  836. {
  837. int quantize_tag = 0;
  838. const caffe::BlobProto& blob = binlayer.blobs(j);
  839. std::vector<float> quantize_table;
  840. std::vector<unsigned char> quantize_index;
  841. std::vector<unsigned short> float16_weights;
  842. // we will not quantize the bias values
  843. if (j == 0 && quantize_level != 0)
  844. {
  845. if (quantize_level == 256)
  846. {
  847. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  848. }
  849. else if (quantize_level == 65536)
  850. {
  851. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  852. }
  853. }
  854. // write quantize tag first
  855. if (j == 0)
  856. fwrite(&quantize_tag, sizeof(int), 1, bp);
  857. if (quantize_tag)
  858. {
  859. int p0 = ftell(bp);
  860. if (quantize_level == 256)
  861. {
  862. // write quantize table and index
  863. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  864. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  865. }
  866. else if (quantize_level == 65536)
  867. {
  868. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  869. }
  870. // padding to 32bit align
  871. int nwrite = ftell(bp) - p0;
  872. int nalign = alignSize(nwrite, 4);
  873. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  874. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  875. }
  876. else
  877. {
  878. // write original data
  879. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  880. }
  881. }
  882. }
  883. else if (layer.type() == "InnerProduct")
  884. {
  885. const caffe::LayerParameter& binlayer = net.layer(netidx);
  886. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  887. const caffe::InnerProductParameter& inner_product_param = layer.inner_product_param();
  888. fprintf(pp, " 0=%d", inner_product_param.num_output());
  889. fprintf(pp, " 1=%d", inner_product_param.bias_term());
  890. fprintf(pp, " 2=%d", weight_blob.data_size());
  891. bool int8_scale_term = false;
  892. std::vector<float> weight_int8scale;
  893. std::vector<float> blob_int8scale;
  894. if (int8scale_table_path)
  895. {
  896. char key[256];
  897. sprintf(key, "%s_param_0", layer.name().c_str());
  898. if (weight_int8scale_table.find(std::string(key)) != weight_int8scale_table.end())
  899. {
  900. weight_int8scale = weight_int8scale_table[std::string(key)];
  901. }
  902. if (blob_int8scale_table.find(layer.name()) != blob_int8scale_table.end())
  903. {
  904. blob_int8scale = blob_int8scale_table[layer.name()];
  905. }
  906. int8_scale_term = !weight_int8scale.empty() && !blob_int8scale.empty();
  907. if (int8_scale_term)
  908. {
  909. fprintf(pp, " 8=1");
  910. }
  911. }
  912. for (int j=0; j<binlayer.blobs_size(); j++)
  913. {
  914. int quantize_tag = 0;
  915. const caffe::BlobProto& blob = binlayer.blobs(j);
  916. std::vector<float> quantize_table;
  917. std::vector<unsigned char> quantize_index;
  918. std::vector<unsigned short> float16_weights;
  919. std::vector<signed char> int8_weights;
  920. // we will not quantize the bias values
  921. if (j == 0)
  922. {
  923. if (int8_scale_term)
  924. {
  925. if (quantize_level == 0)
  926. {
  927. quantize_tag = 0x0002C056;
  928. }
  929. else if (quantize_level == 256)
  930. {
  931. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), weight_int8scale, int8_weights);
  932. }
  933. }
  934. else if (quantize_level == 256)
  935. {
  936. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  937. }
  938. else if (quantize_level == 65536)
  939. {
  940. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  941. }
  942. // write quantize tag first
  943. fwrite(&quantize_tag, sizeof(int), 1, bp);
  944. if (quantize_tag)
  945. {
  946. int p0 = ftell(bp);
  947. if (int8_scale_term)
  948. {
  949. if (quantize_level == 0)
  950. {
  951. // write original data and int8scale
  952. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  953. }
  954. else if (quantize_level == 256)
  955. {
  956. fwrite(int8_weights.data(), sizeof(signed char), int8_weights.size(), bp);
  957. }
  958. }
  959. else if (quantize_level == 256)
  960. {
  961. // write quantize table and index
  962. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  963. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  964. }
  965. else if (quantize_level == 65536)
  966. {
  967. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  968. }
  969. // padding to 32bit align
  970. int nwrite = ftell(bp) - p0;
  971. int nalign = alignSize(nwrite, 4);
  972. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  973. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  974. }
  975. else
  976. {
  977. // write original data
  978. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  979. }
  980. }
  981. else
  982. {
  983. // write original data
  984. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  985. }
  986. }
  987. if (int8_scale_term)
  988. {
  989. // write int8_scale data
  990. fwrite(weight_int8scale.data(), sizeof(float), weight_int8scale.size(), bp);
  991. fwrite(blob_int8scale.data(), sizeof(float), blob_int8scale.size(), bp);
  992. }
  993. }
  994. else if (layer.type() == "Input")
  995. {
  996. const caffe::InputParameter& input_param = layer.input_param();
  997. const caffe::BlobShape& bs = input_param.shape(0);
  998. if (bs.dim_size() == 4)
  999. {
  1000. fprintf(pp, " 0=%ld", bs.dim(3));
  1001. fprintf(pp, " 1=%ld", bs.dim(2));
  1002. fprintf(pp, " 2=%ld", bs.dim(1));
  1003. }
  1004. else if (bs.dim_size() == 3)
  1005. {
  1006. fprintf(pp, " 0=%ld", bs.dim(2));
  1007. fprintf(pp, " 1=%ld", bs.dim(1));
  1008. fprintf(pp, " 2=-233");
  1009. }
  1010. else if (bs.dim_size() == 2)
  1011. {
  1012. fprintf(pp, " 0=%ld", bs.dim(1));
  1013. fprintf(pp, " 1=-233");
  1014. fprintf(pp, " 2=-233");
  1015. }
  1016. }
  1017. else if (layer.type() == "Interp")
  1018. {
  1019. const caffe::InterpParameter& interp_param = layer.interp_param();
  1020. fprintf(pp, " 0=%d", 2);
  1021. fprintf(pp, " 1=%f", (float)interp_param.zoom_factor());
  1022. fprintf(pp, " 2=%f", (float)interp_param.zoom_factor());
  1023. fprintf(pp, " 3=%d", interp_param.height());
  1024. fprintf(pp, " 4=%d", interp_param.width());
  1025. }
  1026. else if (layer.type() == "LRN")
  1027. {
  1028. const caffe::LRNParameter& lrn_param = layer.lrn_param();
  1029. fprintf(pp, " 0=%d", lrn_param.norm_region());
  1030. fprintf(pp, " 1=%d", lrn_param.local_size());
  1031. fprintf(pp, " 2=%f", lrn_param.alpha());
  1032. fprintf(pp, " 3=%f", lrn_param.beta());
  1033. }
  1034. else if (layer.type() == "LSTM")
  1035. {
  1036. const caffe::LayerParameter& binlayer = net.layer(netidx);
  1037. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  1038. const caffe::RecurrentParameter& recurrent_param = layer.recurrent_param();
  1039. fprintf(pp, " 0=%d", recurrent_param.num_output());
  1040. fprintf(pp, " 1=%d", weight_blob.data_size());
  1041. for (int j=0; j<binlayer.blobs_size(); j++)
  1042. {
  1043. int quantize_tag = 0;
  1044. const caffe::BlobProto& blob = binlayer.blobs(j);
  1045. std::vector<float> quantize_table;
  1046. std::vector<unsigned char> quantize_index;
  1047. std::vector<unsigned short> float16_weights;
  1048. if (quantize_level != 0)
  1049. {
  1050. if (quantize_level == 256)
  1051. {
  1052. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  1053. }
  1054. else if (quantize_level == 65536)
  1055. {
  1056. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  1057. }
  1058. }
  1059. // write quantize tag first
  1060. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1061. if (quantize_tag)
  1062. {
  1063. int p0 = ftell(bp);
  1064. if (quantize_level == 256)
  1065. {
  1066. // write quantize table and index
  1067. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  1068. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  1069. }
  1070. else if (quantize_level == 65536)
  1071. {
  1072. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  1073. }
  1074. // padding to 32bit align
  1075. int nwrite = ftell(bp) - p0;
  1076. int nalign = alignSize(nwrite, 4);
  1077. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  1078. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  1079. }
  1080. else
  1081. {
  1082. // write original data
  1083. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  1084. }
  1085. }
  1086. }
  1087. else if (layer.type() == "MemoryData")
  1088. {
  1089. const caffe::MemoryDataParameter& memory_data_param = layer.memory_data_param();
  1090. fprintf(pp, " 0=%d", memory_data_param.width());
  1091. fprintf(pp, " 1=%d", memory_data_param.height());
  1092. fprintf(pp, " 2=%d", memory_data_param.channels());
  1093. }
  1094. else if (layer.type() == "MVN")
  1095. {
  1096. const caffe::MVNParameter& mvn_param = layer.mvn_param();
  1097. fprintf(pp, " 0=%d", mvn_param.normalize_variance());
  1098. fprintf(pp, " 1=%d", mvn_param.across_channels());
  1099. fprintf(pp, " 2=%f", mvn_param.eps());
  1100. }
  1101. else if (layer.type() == "Normalize")
  1102. {
  1103. const caffe::LayerParameter& binlayer = net.layer(netidx);
  1104. const caffe::BlobProto& scale_blob = binlayer.blobs(0);
  1105. const caffe::NormalizeParameter& norm_param = layer.norm_param();
  1106. fprintf(pp, " 0=%d", norm_param.across_spatial());
  1107. fprintf(pp, " 1=%d", norm_param.channel_shared());
  1108. fprintf(pp, " 2=%f", norm_param.eps());
  1109. fprintf(pp, " 3=%d", scale_blob.data_size());
  1110. fwrite(scale_blob.data().data(), sizeof(float), scale_blob.data_size(), bp);
  1111. }
  1112. else if (layer.type() == "Permute")
  1113. {
  1114. const caffe::PermuteParameter& permute_param = layer.permute_param();
  1115. int order_size = permute_param.order_size();
  1116. int order_type = 0;
  1117. if (order_size == 0)
  1118. order_type = 0;
  1119. if (order_size == 1)
  1120. {
  1121. int order0 = permute_param.order(0);
  1122. if (order0 == 0)
  1123. order_type = 0;
  1124. // permute with N not supported
  1125. }
  1126. if (order_size == 2)
  1127. {
  1128. int order0 = permute_param.order(0);
  1129. int order1 = permute_param.order(1);
  1130. if (order0 == 0)
  1131. {
  1132. if (order1 == 1) // 0 1 2 3
  1133. order_type = 0;
  1134. else if (order1 == 2) // 0 2 1 3
  1135. order_type = 2;
  1136. else if (order1 == 3) // 0 3 1 2
  1137. order_type = 4;
  1138. }
  1139. // permute with N not supported
  1140. }
  1141. if (order_size == 3 || order_size == 4)
  1142. {
  1143. int order0 = permute_param.order(0);
  1144. int order1 = permute_param.order(1);
  1145. int order2 = permute_param.order(2);
  1146. if (order0 == 0)
  1147. {
  1148. if (order1 == 1)
  1149. {
  1150. if (order2 == 2) // 0 1 2 3
  1151. order_type = 0;
  1152. if (order2 == 3) // 0 1 3 2
  1153. order_type = 1;
  1154. }
  1155. else if (order1 == 2)
  1156. {
  1157. if (order2 == 1) // 0 2 1 3
  1158. order_type = 2;
  1159. if (order2 == 3) // 0 2 3 1
  1160. order_type = 3;
  1161. }
  1162. else if (order1 == 3)
  1163. {
  1164. if (order2 == 1) // 0 3 1 2
  1165. order_type = 4;
  1166. if (order2 == 2) // 0 3 2 1
  1167. order_type = 5;
  1168. }
  1169. }
  1170. // permute with N not supported
  1171. }
  1172. fprintf(pp, " 0=%d", order_type);
  1173. }
  1174. else if (layer.type() == "Pooling")
  1175. {
  1176. const caffe::PoolingParameter& pooling_param = layer.pooling_param();
  1177. fprintf(pp, " 0=%d", pooling_param.pool());
  1178. if (pooling_param.has_kernel_w() && pooling_param.has_kernel_h())
  1179. {
  1180. fprintf(pp, " 1=%d", pooling_param.kernel_w());
  1181. fprintf(pp, " 11=%d", pooling_param.kernel_h());
  1182. }
  1183. else
  1184. {
  1185. fprintf(pp, " 1=%d", pooling_param.kernel_size());
  1186. }
  1187. if (pooling_param.has_stride_w() && pooling_param.has_stride_h())
  1188. {
  1189. fprintf(pp, " 2=%d", pooling_param.stride_w());
  1190. fprintf(pp, " 12=%d", pooling_param.stride_h());
  1191. }
  1192. else
  1193. {
  1194. fprintf(pp, " 2=%d", pooling_param.stride());
  1195. }
  1196. if (pooling_param.has_pad_w() && pooling_param.has_pad_h())
  1197. {
  1198. fprintf(pp, " 3=%d", pooling_param.pad_w());
  1199. fprintf(pp, " 13=%d", pooling_param.pad_h());
  1200. }
  1201. else
  1202. {
  1203. fprintf(pp, " 3=%d", pooling_param.pad());
  1204. }
  1205. fprintf(pp, " 4=%d", pooling_param.has_global_pooling() ? pooling_param.global_pooling() : 0);
  1206. }
  1207. else if (layer.type() == "Power")
  1208. {
  1209. const caffe::PowerParameter& power_param = layer.power_param();
  1210. fprintf(pp, " 0=%f", power_param.power());
  1211. fprintf(pp, " 1=%f", power_param.scale());
  1212. fprintf(pp, " 2=%f", power_param.shift());
  1213. }
  1214. else if (layer.type() == "PReLU")
  1215. {
  1216. const caffe::LayerParameter& binlayer = net.layer(netidx);
  1217. const caffe::BlobProto& slope_blob = binlayer.blobs(0);
  1218. fprintf(pp, " 0=%d", slope_blob.data_size());
  1219. fwrite(slope_blob.data().data(), sizeof(float), slope_blob.data_size(), bp);
  1220. }
  1221. else if (layer.type() == "PriorBox")
  1222. {
  1223. const caffe::PriorBoxParameter& prior_box_param = layer.prior_box_param();
  1224. int num_aspect_ratio = prior_box_param.aspect_ratio_size();
  1225. for (int j=0; j<prior_box_param.aspect_ratio_size(); j++)
  1226. {
  1227. float ar = prior_box_param.aspect_ratio(j);
  1228. if (fabs(ar - 1.) < 1e-6) {
  1229. num_aspect_ratio--;
  1230. }
  1231. }
  1232. float variances[4] = {0.1f, 0.1f, 0.1f, 0.1f};
  1233. if (prior_box_param.variance_size() == 4)
  1234. {
  1235. variances[0] = prior_box_param.variance(0);
  1236. variances[1] = prior_box_param.variance(1);
  1237. variances[2] = prior_box_param.variance(2);
  1238. variances[3] = prior_box_param.variance(3);
  1239. }
  1240. else if (prior_box_param.variance_size() == 1)
  1241. {
  1242. variances[0] = prior_box_param.variance(0);
  1243. variances[1] = prior_box_param.variance(0);
  1244. variances[2] = prior_box_param.variance(0);
  1245. variances[3] = prior_box_param.variance(0);
  1246. }
  1247. int flip = prior_box_param.has_flip() ? prior_box_param.flip() : 1;
  1248. int clip = prior_box_param.has_clip() ? prior_box_param.clip() : 0;
  1249. int image_width = -233;
  1250. int image_height = -233;
  1251. if (prior_box_param.has_img_size())
  1252. {
  1253. image_width = prior_box_param.img_size();
  1254. image_height = prior_box_param.img_size();
  1255. }
  1256. else if (prior_box_param.has_img_w() && prior_box_param.has_img_h())
  1257. {
  1258. image_width = prior_box_param.img_w();
  1259. image_height = prior_box_param.img_h();
  1260. }
  1261. float step_width = -233;
  1262. float step_height = -233;
  1263. if (prior_box_param.has_step())
  1264. {
  1265. step_width = prior_box_param.step();
  1266. step_height = prior_box_param.step();
  1267. }
  1268. else if (prior_box_param.has_step_w() && prior_box_param.has_step_h())
  1269. {
  1270. step_width = prior_box_param.step_w();
  1271. step_height = prior_box_param.step_h();
  1272. }
  1273. fprintf(pp, " -23300=%d", prior_box_param.min_size_size());
  1274. for (int j=0; j<prior_box_param.min_size_size(); j++)
  1275. {
  1276. fprintf(pp, ",%f", prior_box_param.min_size(j));
  1277. }
  1278. fprintf(pp, " -23301=%d", prior_box_param.max_size_size());
  1279. for (int j=0; j<prior_box_param.max_size_size(); j++)
  1280. {
  1281. fprintf(pp, ",%f", prior_box_param.max_size(j));
  1282. }
  1283. fprintf(pp, " -23302=%d", num_aspect_ratio);
  1284. for (int j=0; j<prior_box_param.aspect_ratio_size(); j++)
  1285. {
  1286. float ar = prior_box_param.aspect_ratio(j);
  1287. if (fabs(ar - 1.) < 1e-6) {
  1288. continue;
  1289. }
  1290. fprintf(pp, ",%f", ar);
  1291. }
  1292. fprintf(pp, " 3=%f", variances[0]);
  1293. fprintf(pp, " 4=%f", variances[1]);
  1294. fprintf(pp, " 5=%f", variances[2]);
  1295. fprintf(pp, " 6=%f", variances[3]);
  1296. fprintf(pp, " 7=%d", flip);
  1297. fprintf(pp, " 8=%d", clip);
  1298. fprintf(pp, " 9=%d", image_width);
  1299. fprintf(pp, " 10=%d", image_height);
  1300. fprintf(pp, " 11=%f", step_width);
  1301. fprintf(pp, " 12=%f", step_height);
  1302. fprintf(pp, " 13=%f", prior_box_param.offset());
  1303. }
  1304. else if (layer.type() == "PSROIPooling")
  1305. {
  1306. const caffe::PSROIPoolingParameter& psroi_pooling_param = layer.psroi_pooling_param();
  1307. fprintf(pp, " 0=%d", psroi_pooling_param.group_size());
  1308. fprintf(pp, " 1=%d", psroi_pooling_param.group_size());
  1309. fprintf(pp, " 2=%f", psroi_pooling_param.spatial_scale());
  1310. fprintf(pp, " 3=%d", psroi_pooling_param.output_dim());
  1311. }
  1312. else if (layer.type() == "Python")
  1313. {
  1314. const caffe::PythonParameter& python_param = layer.python_param();
  1315. std::string python_layer_name = python_param.layer();
  1316. if (python_layer_name == "ProposalLayer")
  1317. {
  1318. int feat_stride = 16;
  1319. sscanf(python_param.param_str().c_str(), "'feat_stride': %d", &feat_stride);
  1320. int base_size = 16;
  1321. // float ratio;
  1322. // float scale;
  1323. int pre_nms_topN = 6000;
  1324. int after_nms_topN = 300;
  1325. float nms_thresh = 0.7;
  1326. int min_size = 16;
  1327. fprintf(pp, " 0=%d", feat_stride);
  1328. fprintf(pp, " 1=%d", base_size);
  1329. fprintf(pp, " 2=%d", pre_nms_topN);
  1330. fprintf(pp, " 3=%d", after_nms_topN);
  1331. fprintf(pp, " 4=%f", nms_thresh);
  1332. fprintf(pp, " 5=%d", min_size);
  1333. }
  1334. }
  1335. else if (layer.type() == "ReLU")
  1336. {
  1337. const caffe::ReLUParameter& relu_param = layer.relu_param();
  1338. if (relu_param.has_negative_slope())
  1339. {
  1340. fprintf(pp, " 0=%f", relu_param.negative_slope());
  1341. }
  1342. }
  1343. else if (layer.type() == "ReLU6")
  1344. {
  1345. float min = 0.f;
  1346. float max = 6.f;
  1347. fprintf(pp, " 0=%f", min);
  1348. fprintf(pp, " 1=%f", max);
  1349. }
  1350. else if (layer.type() == "Reorg")
  1351. {
  1352. const caffe::ReorgParameter& reorg_param = layer.reorg_param();
  1353. fprintf(pp, " 0=%d", reorg_param.stride());
  1354. }
  1355. else if (layer.type() == "Reshape")
  1356. {
  1357. const caffe::ReshapeParameter& reshape_param = layer.reshape_param();
  1358. const caffe::BlobShape& bs = reshape_param.shape();
  1359. if (bs.dim_size() == 1)
  1360. {
  1361. fprintf(pp, " 0=%ld 1=-233 2=-233", bs.dim(0));
  1362. }
  1363. else if (bs.dim_size() == 2)
  1364. {
  1365. fprintf(pp, " 0=%ld 1=-233 2=-233", bs.dim(1));
  1366. }
  1367. else if (bs.dim_size() == 3)
  1368. {
  1369. fprintf(pp, " 0=%ld 1=%ld 2=-233", bs.dim(2), bs.dim(1));
  1370. }
  1371. else // bs.dim_size() == 4
  1372. {
  1373. fprintf(pp, " 0=%ld 1=%ld 2=%ld", bs.dim(3), bs.dim(2), bs.dim(1));
  1374. }
  1375. fprintf(pp, " 3=0");// permute
  1376. }
  1377. else if (layer.type() == "ROIAlign")
  1378. {
  1379. const caffe::ROIAlignParameter& roi_align_param = layer.roi_align_param();
  1380. fprintf(pp, " 0=%d", roi_align_param.pooled_w());
  1381. fprintf(pp, " 1=%d", roi_align_param.pooled_h());
  1382. fprintf(pp, " 2=%f", roi_align_param.spatial_scale());
  1383. }
  1384. else if (layer.type() == "ROIPooling")
  1385. {
  1386. const caffe::ROIPoolingParameter& roi_pooling_param = layer.roi_pooling_param();
  1387. fprintf(pp, " 0=%d", roi_pooling_param.pooled_w());
  1388. fprintf(pp, " 1=%d", roi_pooling_param.pooled_h());
  1389. fprintf(pp, " 2=%f", roi_pooling_param.spatial_scale());
  1390. }
  1391. else if (layer.type() == "Scale")
  1392. {
  1393. const caffe::LayerParameter& binlayer = net.layer(netidx);
  1394. const caffe::ScaleParameter& scale_param = layer.scale_param();
  1395. bool scale_weight = scale_param.bias_term() ? (binlayer.blobs_size() == 2) : (binlayer.blobs_size() == 1);
  1396. if (scale_weight)
  1397. {
  1398. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  1399. fprintf(pp, " 0=%d", (int)weight_blob.data_size());
  1400. }
  1401. else
  1402. {
  1403. fprintf(pp, " 0=-233");
  1404. }
  1405. fprintf(pp, " 1=%d", scale_param.bias_term());
  1406. for (int j=0; j<binlayer.blobs_size(); j++)
  1407. {
  1408. const caffe::BlobProto& blob = binlayer.blobs(j);
  1409. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  1410. }
  1411. }
  1412. else if (layer.type() == "ShuffleChannel")
  1413. {
  1414. const caffe::ShuffleChannelParameter& shuffle_channel_param = layer.shuffle_channel_param();
  1415. fprintf(pp, " 0=%d", shuffle_channel_param.group());
  1416. }
  1417. else if (layer.type() == "Slice")
  1418. {
  1419. const caffe::SliceParameter& slice_param = layer.slice_param();
  1420. if (slice_param.slice_point_size() == 0)
  1421. {
  1422. int num_slice = layer.top_size();
  1423. fprintf(pp, " -23300=%d", num_slice);
  1424. for (int j=0; j<num_slice; j++)
  1425. {
  1426. fprintf(pp, ",-233");
  1427. }
  1428. }
  1429. else
  1430. {
  1431. int num_slice = slice_param.slice_point_size() + 1;
  1432. fprintf(pp, " -23300=%d", num_slice);
  1433. int prev_offset = 0;
  1434. for (int j=0; j<slice_param.slice_point_size(); j++)
  1435. {
  1436. int offset = slice_param.slice_point(j);
  1437. fprintf(pp, ",%d", offset - prev_offset);
  1438. prev_offset = offset;
  1439. }
  1440. fprintf(pp, ",-233");
  1441. }
  1442. int dim = slice_param.axis() - 1;
  1443. fprintf(pp, " 1=%d", dim);
  1444. }
  1445. else if (layer.type() == "Softmax")
  1446. {
  1447. const caffe::SoftmaxParameter& softmax_param = layer.softmax_param();
  1448. int dim = softmax_param.axis() - 1;
  1449. fprintf(pp, " 0=%d", dim);
  1450. fprintf(pp, " 1=1");
  1451. }
  1452. else if (layer.type() == "Threshold")
  1453. {
  1454. const caffe::ThresholdParameter& threshold_param = layer.threshold_param();
  1455. fprintf(pp, " 0=%f", threshold_param.threshold());
  1456. }
  1457. else if (layer.type() == "YoloDetectionOutput")
  1458. {
  1459. const caffe::YoloDetectionOutputParameter& yolo_detection_output_param = layer.yolo_detection_output_param();
  1460. fprintf(pp, " 0=%d", yolo_detection_output_param.num_classes());
  1461. fprintf(pp, " 1=%d", yolo_detection_output_param.num_box());
  1462. fprintf(pp, " 2=%f", yolo_detection_output_param.confidence_threshold());
  1463. fprintf(pp, " 3=%f", yolo_detection_output_param.nms_threshold());
  1464. int num_bias = yolo_detection_output_param.biases_size();
  1465. fprintf(pp, " -23304=%d", num_bias);
  1466. for (int j=0; j<num_bias; j++)
  1467. {
  1468. fprintf(pp, ",%f", yolo_detection_output_param.biases(j));
  1469. }
  1470. }
  1471. else if (layer.type() == "Yolov3DetectionOutput")
  1472. {
  1473. const caffe::Yolov3DetectionOutputParameter& yolov3_detection_output_param = layer.yolov3_detection_output_param();
  1474. fprintf(pp, " 0=%d", yolov3_detection_output_param.num_classes());
  1475. fprintf(pp, " 1=%d", yolov3_detection_output_param.num_box());
  1476. fprintf(pp, " 2=%f", yolov3_detection_output_param.confidence_threshold());
  1477. fprintf(pp, " 3=%f", yolov3_detection_output_param.nms_threshold());
  1478. int num_bias = yolov3_detection_output_param.biases_size();
  1479. fprintf(pp, " -23304=%d", num_bias);
  1480. for (int j = 0; j<num_bias; j++)
  1481. {
  1482. fprintf(pp, ",%f", yolov3_detection_output_param.biases(j));
  1483. }
  1484. int num_mask = yolov3_detection_output_param.mask_size();
  1485. fprintf(pp, " -23305=%d", num_mask);
  1486. for (int j = 0; j<num_mask; j++)
  1487. {
  1488. fprintf(pp, ",%f", (float)yolov3_detection_output_param.mask(j));
  1489. }
  1490. int num_anchors = yolov3_detection_output_param.anchors_scale_size();
  1491. fprintf(pp, " -23306=%d", num_anchors);
  1492. for (int j = 0; j<num_anchors; j++)
  1493. {
  1494. fprintf(pp, ",%f", (float)yolov3_detection_output_param.anchors_scale(j));
  1495. }
  1496. fprintf(pp, " 7=%d", yolov3_detection_output_param.mask_group_num());
  1497. }
  1498. fprintf(pp, "\n");
  1499. // add split layer if top reference larger than one
  1500. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  1501. {
  1502. std::string blob_name = blob_name_decorated[layer.top(0)];
  1503. if (bottom_reference.find(blob_name) != bottom_reference.end())
  1504. {
  1505. int refcount = bottom_reference[blob_name];
  1506. if (refcount > 1)
  1507. {
  1508. char splitname[256];
  1509. sprintf(splitname, "splitncnn_%d", internal_split);
  1510. fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount);
  1511. fprintf(pp, " %s", blob_name.c_str());
  1512. for (int j=0; j<refcount; j++)
  1513. {
  1514. fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j);
  1515. }
  1516. fprintf(pp, "\n");
  1517. internal_split++;
  1518. }
  1519. }
  1520. }
  1521. else
  1522. {
  1523. for (int j=0; j<layer.top_size(); j++)
  1524. {
  1525. std::string blob_name = layer.top(j);
  1526. if (bottom_reference.find(blob_name) != bottom_reference.end())
  1527. {
  1528. int refcount = bottom_reference[blob_name];
  1529. if (refcount > 1)
  1530. {
  1531. char splitname[256];
  1532. sprintf(splitname, "splitncnn_%d", internal_split);
  1533. fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount);
  1534. fprintf(pp, " %s", blob_name.c_str());
  1535. for (int j=0; j<refcount; j++)
  1536. {
  1537. fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j);
  1538. }
  1539. fprintf(pp, "\n");
  1540. internal_split++;
  1541. }
  1542. }
  1543. }
  1544. }
  1545. }
  1546. fclose(pp);
  1547. fclose(bp);
  1548. return 0;
  1549. }