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 40 kB

8 years ago
8 years ago
8 years ago
8 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  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 <algorithm>
  21. #include <google/protobuf/io/coded_stream.h>
  22. #include <google/protobuf/io/zero_copy_stream_impl.h>
  23. #include <google/protobuf/text_format.h>
  24. #include <google/protobuf/message.h>
  25. #include "caffe.pb.h"
  26. static inline size_t alignSize(size_t sz, int n)
  27. {
  28. return (sz + n-1) & -n;
  29. }
  30. // convert float to half precision floating point
  31. static unsigned short float2half(float value)
  32. {
  33. // 1 : 8 : 23
  34. union
  35. {
  36. unsigned int u;
  37. float f;
  38. } tmp;
  39. tmp.f = value;
  40. // 1 : 8 : 23
  41. unsigned short sign = (tmp.u & 0x80000000) >> 31;
  42. unsigned short exponent = (tmp.u & 0x7F800000) >> 23;
  43. unsigned int significand = tmp.u & 0x7FFFFF;
  44. // fprintf(stderr, "%d %d %d\n", sign, exponent, significand);
  45. // 1 : 5 : 10
  46. unsigned short fp16;
  47. if (exponent == 0)
  48. {
  49. // zero or denormal, always underflow
  50. fp16 = (sign << 15) | (0x00 << 10) | 0x00;
  51. }
  52. else if (exponent == 0xFF)
  53. {
  54. // infinity or NaN
  55. fp16 = (sign << 15) | (0x1F << 10) | (significand ? 0x200 : 0x00);
  56. }
  57. else
  58. {
  59. // normalized
  60. short newexp = exponent + (- 127 + 15);
  61. if (newexp >= 31)
  62. {
  63. // overflow, return infinity
  64. fp16 = (sign << 15) | (0x1F << 10) | 0x00;
  65. }
  66. else if (newexp <= 0)
  67. {
  68. // underflow
  69. if (newexp >= -10)
  70. {
  71. // denormal half-precision
  72. unsigned short sig = (significand | 0x800000) >> (14 - newexp);
  73. fp16 = (sign << 15) | (0x00 << 10) | sig;
  74. }
  75. else
  76. {
  77. // underflow
  78. fp16 = (sign << 15) | (0x00 << 10) | 0x00;
  79. }
  80. }
  81. else
  82. {
  83. fp16 = (sign << 15) | (newexp << 10) | (significand >> 13);
  84. }
  85. }
  86. return fp16;
  87. }
  88. static int quantize_weight(float *data, size_t data_length, std::vector<unsigned short>& float16_weights)
  89. {
  90. float16_weights.resize(data_length);
  91. for (size_t i = 0; i < data_length; i++)
  92. {
  93. float f = data[i];
  94. unsigned short fp16 = float2half(f);
  95. float16_weights[i] = fp16;
  96. }
  97. // magic tag for half-precision floating point
  98. return 0x01306B47;
  99. }
  100. static bool quantize_weight(float *data, size_t data_length, int quantize_level, std::vector<float> &quantize_table, std::vector<unsigned char> &quantize_index) {
  101. assert(quantize_level != 0);
  102. assert(data != NULL);
  103. assert(data_length > 0);
  104. if (data_length < static_cast<size_t>(quantize_level)) {
  105. fprintf(stderr, "No need quantize,because: data_length < quantize_level");
  106. return false;
  107. }
  108. quantize_table.reserve(quantize_level);
  109. quantize_index.reserve(data_length);
  110. // 1. Find min and max value
  111. float max_value = std::numeric_limits<float>::min();
  112. float min_value = std::numeric_limits<float>::max();
  113. for (size_t i = 0; i < data_length; ++i)
  114. {
  115. if (max_value < data[i]) max_value = data[i];
  116. if (min_value > data[i]) min_value = data[i];
  117. }
  118. float strides = (max_value - min_value) / quantize_level;
  119. // 2. Generate quantize table
  120. for (int i = 0; i < quantize_level; ++i)
  121. {
  122. quantize_table.push_back(min_value + i * strides);
  123. }
  124. // 3. Align data to the quantized value
  125. for (size_t i = 0; i < data_length; ++i)
  126. {
  127. size_t table_index = int((data[i] - min_value) / strides);
  128. table_index = std::min<float>(table_index, quantize_level - 1);
  129. float low_value = quantize_table[table_index];
  130. float high_value = low_value + strides;
  131. // find a nearest value between low and high value.
  132. float targetValue = data[i] - low_value < high_value - data[i] ? low_value : high_value;
  133. table_index = int((targetValue - min_value) / strides);
  134. table_index = std::min<float>(table_index, quantize_level - 1);
  135. quantize_index.push_back(table_index);
  136. }
  137. return true;
  138. }
  139. static bool read_proto_from_text(const char* filepath, google::protobuf::Message* message)
  140. {
  141. std::ifstream fs(filepath, std::ifstream::in);
  142. if (!fs.is_open())
  143. {
  144. fprintf(stderr, "open failed %s\n", filepath);
  145. return false;
  146. }
  147. google::protobuf::io::IstreamInputStream input(&fs);
  148. bool success = google::protobuf::TextFormat::Parse(&input, message);
  149. fs.close();
  150. return success;
  151. }
  152. static bool read_proto_from_binary(const char* filepath, google::protobuf::Message* message)
  153. {
  154. std::ifstream fs(filepath, std::ifstream::in | std::ifstream::binary);
  155. if (!fs.is_open())
  156. {
  157. fprintf(stderr, "open failed %s\n", filepath);
  158. return false;
  159. }
  160. google::protobuf::io::IstreamInputStream input(&fs);
  161. google::protobuf::io::CodedInputStream codedstr(&input);
  162. codedstr.SetTotalBytesLimit(INT_MAX, INT_MAX / 2);
  163. bool success = message->ParseFromCodedStream(&codedstr);
  164. fs.close();
  165. return success;
  166. }
  167. int main(int argc, char** argv)
  168. {
  169. if (!(argc == 3 || argc == 5 || argc == 6))
  170. {
  171. fprintf(stderr, "Usage: %s [caffeproto] [caffemodel] [ncnnproto] [ncnnbin] [quantizelevel]\n", argv[0]);
  172. return -1;
  173. }
  174. const char* caffeproto = argv[1];
  175. const char* caffemodel = argv[2];
  176. const char* ncnn_prototxt = argc >= 5 ? argv[3] : "ncnn.proto";
  177. const char* ncnn_modelbin = argc >= 5 ? argv[4] : "ncnn.bin";
  178. const char* quantize_param = argc == 6 ? argv[5] : "0";
  179. int quantize_level = atoi(quantize_param);
  180. if (quantize_level != 0 && quantize_level != 256 && quantize_level != 65536) {
  181. fprintf(stderr, "%s: only support quantize level = 0, 256, or 65536", argv[0]);
  182. return -1;
  183. }
  184. caffe::NetParameter proto;
  185. caffe::NetParameter net;
  186. // load
  187. bool s0 = read_proto_from_text(caffeproto, &proto);
  188. if (!s0)
  189. {
  190. fprintf(stderr, "read_proto_from_text failed\n");
  191. return -1;
  192. }
  193. bool s1 = read_proto_from_binary(caffemodel, &net);
  194. if (!s1)
  195. {
  196. fprintf(stderr, "read_proto_from_binary failed\n");
  197. return -1;
  198. }
  199. FILE* pp = fopen(ncnn_prototxt, "wb");
  200. FILE* bp = fopen(ncnn_modelbin, "wb");
  201. // magic
  202. fprintf(pp, "7767517\n");
  203. // rename mapping for identical bottom top style
  204. std::map<std::string, std::string> blob_name_decorated;
  205. // bottom blob reference
  206. std::map<std::string, int> bottom_reference;
  207. // global definition line
  208. // [layer count] [blob count]
  209. int layer_count = proto.layer_size();
  210. std::set<std::string> blob_names;
  211. for (int i=0; i<layer_count; i++)
  212. {
  213. const caffe::LayerParameter& layer = proto.layer(i);
  214. for (int j=0; j<layer.bottom_size(); j++)
  215. {
  216. std::string blob_name = layer.bottom(j);
  217. if (blob_name_decorated.find(blob_name) != blob_name_decorated.end())
  218. {
  219. blob_name = blob_name_decorated[blob_name];
  220. }
  221. blob_names.insert(blob_name);
  222. if (bottom_reference.find(blob_name) == bottom_reference.end())
  223. {
  224. bottom_reference[blob_name] = 1;
  225. }
  226. else
  227. {
  228. bottom_reference[blob_name] = bottom_reference[blob_name] + 1;
  229. }
  230. }
  231. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  232. {
  233. std::string blob_name = layer.top(0) + "_" + layer.name();
  234. blob_name_decorated[layer.top(0)] = blob_name;
  235. blob_names.insert(blob_name);
  236. }
  237. else
  238. {
  239. for (int j=0; j<layer.top_size(); j++)
  240. {
  241. std::string blob_name = layer.top(j);
  242. blob_names.insert(blob_name);
  243. }
  244. }
  245. }
  246. // remove bottom_reference entry with reference equals to one
  247. int splitncnn_blob_count = 0;
  248. std::map<std::string, int>::iterator it = bottom_reference.begin();
  249. while (it != bottom_reference.end())
  250. {
  251. if (it->second == 1)
  252. {
  253. bottom_reference.erase(it++);
  254. }
  255. else
  256. {
  257. splitncnn_blob_count += it->second;
  258. // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second);
  259. ++it;
  260. }
  261. }
  262. fprintf(pp, "%lu %lu\n", layer_count + bottom_reference.size(), blob_names.size() + splitncnn_blob_count);
  263. // populate
  264. blob_name_decorated.clear();
  265. int internal_split = 0;
  266. for (int i=0; i<layer_count; i++)
  267. {
  268. const caffe::LayerParameter& layer = proto.layer(i);
  269. // layer definition line, repeated
  270. // [type] [name] [bottom blob count] [top blob count] [bottom blobs] [top blobs] [layer specific params]
  271. if (layer.type() == "Convolution")
  272. {
  273. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  274. if (convolution_param.group() != 1)
  275. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  276. else
  277. fprintf(pp, "%-16s", "Convolution");
  278. }
  279. else if (layer.type() == "Python")
  280. {
  281. const caffe::PythonParameter& python_param = layer.python_param();
  282. std::string python_layer_name = python_param.layer();
  283. if (python_layer_name == "ProposalLayer")
  284. fprintf(pp, "%-16s", "Proposal");
  285. else
  286. fprintf(pp, "%-16s", python_layer_name.c_str());
  287. }
  288. else
  289. {
  290. fprintf(pp, "%-16s", layer.type().c_str());
  291. }
  292. fprintf(pp, " %-16s %d %d", layer.name().c_str(), layer.bottom_size(), layer.top_size());
  293. for (int j=0; j<layer.bottom_size(); j++)
  294. {
  295. std::string blob_name = layer.bottom(j);
  296. if (blob_name_decorated.find(layer.bottom(j)) != blob_name_decorated.end())
  297. {
  298. blob_name = blob_name_decorated[layer.bottom(j)];
  299. }
  300. if (bottom_reference.find(blob_name) != bottom_reference.end())
  301. {
  302. int refidx = bottom_reference[blob_name] - 1;
  303. bottom_reference[blob_name] = refidx;
  304. char splitsuffix[256];
  305. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  306. blob_name = blob_name + splitsuffix;
  307. }
  308. fprintf(pp, " %s", blob_name.c_str());
  309. }
  310. // decorated
  311. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  312. {
  313. std::string blob_name = layer.top(0) + "_" + layer.name();
  314. blob_name_decorated[layer.top(0)] = blob_name;
  315. fprintf(pp, " %s", blob_name.c_str());
  316. }
  317. else
  318. {
  319. for (int j=0; j<layer.top_size(); j++)
  320. {
  321. std::string blob_name = layer.top(j);
  322. fprintf(pp, " %s", blob_name.c_str());
  323. }
  324. }
  325. // find blob binary by layer name
  326. int netidx;
  327. for (netidx=0; netidx<net.layer_size(); netidx++)
  328. {
  329. if (net.layer(netidx).name() == layer.name())
  330. {
  331. break;
  332. }
  333. }
  334. // layer specific params
  335. if (layer.type() == "BatchNorm")
  336. {
  337. const caffe::LayerParameter& binlayer = net.layer(netidx);
  338. const caffe::BlobProto& mean_blob = binlayer.blobs(0);
  339. const caffe::BlobProto& var_blob = binlayer.blobs(1);
  340. fprintf(pp, " 0=%d", (int)mean_blob.data_size());
  341. const caffe::BatchNormParameter& batch_norm_param = layer.batch_norm_param();
  342. float eps = batch_norm_param.eps();
  343. std::vector<float> ones(mean_blob.data_size(), 1.f);
  344. fwrite(ones.data(), sizeof(float), ones.size(), bp);// slope
  345. if (binlayer.blobs_size() < 3)
  346. {
  347. fwrite(mean_blob.data().data(), sizeof(float), mean_blob.data_size(), bp);
  348. float tmp;
  349. for (int j=0; j<var_blob.data_size(); j++)
  350. {
  351. tmp = var_blob.data().data()[j] + eps;
  352. fwrite(&tmp, sizeof(float), 1, bp);
  353. }
  354. }
  355. else
  356. {
  357. float scale_factor = 1 / binlayer.blobs(2).data().data()[0];
  358. // premultiply scale_factor to mean and variance
  359. float tmp;
  360. for (int j=0; j<mean_blob.data_size(); j++)
  361. {
  362. tmp = mean_blob.data().data()[j] * scale_factor;
  363. fwrite(&tmp, sizeof(float), 1, bp);
  364. }
  365. for (int j=0; j<var_blob.data_size(); j++)
  366. {
  367. tmp = var_blob.data().data()[j] * scale_factor + eps;
  368. fwrite(&tmp, sizeof(float), 1, bp);
  369. }
  370. }
  371. std::vector<float> zeros(mean_blob.data_size(), 0.f);
  372. fwrite(zeros.data(), sizeof(float), zeros.size(), bp);// bias
  373. }
  374. else if (layer.type() == "Concat")
  375. {
  376. const caffe::ConcatParameter& concat_param = layer.concat_param();
  377. int dim = concat_param.axis() - 1;
  378. fprintf(pp, " 0=%d", dim);
  379. }
  380. else if (layer.type() == "Convolution")
  381. {
  382. const caffe::LayerParameter& binlayer = net.layer(netidx);
  383. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  384. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  385. fprintf(pp, " 0=%d", convolution_param.num_output());
  386. fprintf(pp, " 1=%d", convolution_param.kernel_size(0));
  387. fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1);
  388. fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1);
  389. fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0);
  390. fprintf(pp, " 5=%d", convolution_param.bias_term());
  391. fprintf(pp, " 6=%d", weight_blob.data_size());
  392. if (convolution_param.group() != 1)
  393. {
  394. fprintf(pp, " 7=%d", convolution_param.group());
  395. }
  396. for (int j = 0; j < binlayer.blobs_size(); j++)
  397. {
  398. int quantize_tag = 0;
  399. const caffe::BlobProto& blob = binlayer.blobs(j);
  400. std::vector<float> quantize_table;
  401. std::vector<unsigned char> quantize_index;
  402. std::vector<unsigned short> float16_weights;
  403. // we will not quantize the bias values
  404. if (j == 0 && quantize_level != 0)
  405. {
  406. if (quantize_level == 256)
  407. {
  408. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  409. }
  410. else if (quantize_level == 65536)
  411. {
  412. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  413. }
  414. }
  415. // write quantize tag first
  416. if (j == 0)
  417. fwrite(&quantize_tag, sizeof(int), 1, bp);
  418. if (quantize_tag)
  419. {
  420. int p0 = ftell(bp);
  421. if (quantize_level == 256)
  422. {
  423. // write quantize table and index
  424. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  425. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  426. }
  427. else if (quantize_level == 65536)
  428. {
  429. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  430. }
  431. // padding to 32bit align
  432. int nwrite = ftell(bp) - p0;
  433. int nalign = alignSize(nwrite, 4);
  434. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  435. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  436. }
  437. else
  438. {
  439. // write original data
  440. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  441. }
  442. }
  443. }
  444. else if (layer.type() == "Crop")
  445. {
  446. const caffe::CropParameter& crop_param = layer.crop_param();
  447. int num_offset = crop_param.offset_size();
  448. int woffset = (num_offset == 2) ? crop_param.offset(0) : 0;
  449. int hoffset = (num_offset == 2) ? crop_param.offset(1) : 0;
  450. fprintf(pp, " 0=%d", woffset);
  451. fprintf(pp, " 1=%d", hoffset);
  452. }
  453. else if (layer.type() == "Deconvolution")
  454. {
  455. const caffe::LayerParameter& binlayer = net.layer(netidx);
  456. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  457. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  458. fprintf(pp, " 0=%d", convolution_param.num_output());
  459. fprintf(pp, " 1=%d", convolution_param.kernel_size(0));
  460. fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1);
  461. fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1);
  462. fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0);
  463. fprintf(pp, " 5=%d", convolution_param.bias_term());
  464. fprintf(pp, " 6=%d", weight_blob.data_size());
  465. int quantized_weight = 0;
  466. fwrite(&quantized_weight, sizeof(int), 1, bp);
  467. // reorder weight from inch-outch to outch-inch
  468. int ksize = convolution_param.kernel_size(0);
  469. int num_output = convolution_param.num_output();
  470. int num_input = weight_blob.data_size() / (ksize * ksize) / num_output;
  471. const float* weight_data_ptr = weight_blob.data().data();
  472. for (int k=0; k<num_output; k++)
  473. {
  474. for (int j=0; j<num_input; j++)
  475. {
  476. fwrite(weight_data_ptr + (j*num_output + k) * ksize * ksize, sizeof(float), ksize * ksize, bp);
  477. }
  478. }
  479. for (int j=1; j<binlayer.blobs_size(); j++)
  480. {
  481. const caffe::BlobProto& blob = binlayer.blobs(j);
  482. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  483. }
  484. }
  485. else if (layer.type() == "DetectionOutput")
  486. {
  487. const caffe::DetectionOutputParameter& detection_output_param = layer.detection_output_param();
  488. const caffe::NonMaximumSuppressionParameter& nms_param = detection_output_param.nms_param();
  489. fprintf(pp, " 0=%d", detection_output_param.num_classes());
  490. fprintf(pp, " 1=%f", nms_param.nms_threshold());
  491. fprintf(pp, " 2=%d", nms_param.top_k());
  492. fprintf(pp, " 3=%d", detection_output_param.keep_top_k());
  493. fprintf(pp, " 4=%f", detection_output_param.confidence_threshold());
  494. }
  495. else if (layer.type() == "Dropout")
  496. {
  497. const caffe::DropoutParameter& dropout_param = layer.dropout_param();
  498. if (!dropout_param.scale_train())
  499. {
  500. float scale = 1.f - dropout_param.dropout_ratio();
  501. fprintf(pp, " 0=%f", scale);
  502. }
  503. }
  504. else if (layer.type() == "Eltwise")
  505. {
  506. const caffe::EltwiseParameter& eltwise_param = layer.eltwise_param();
  507. int coeff_size = eltwise_param.coeff_size();
  508. fprintf(pp, " 0=%d", (int)eltwise_param.operation());
  509. fprintf(pp, " -23301=%d", coeff_size);
  510. for (int j=0; j<coeff_size; j++)
  511. {
  512. fprintf(pp, ",%f", eltwise_param.coeff(j));
  513. }
  514. }
  515. else if (layer.type() == "ELU")
  516. {
  517. const caffe::ELUParameter& elu_param = layer.elu_param();
  518. fprintf(pp, " 0=%f", elu_param.alpha());
  519. }
  520. else if (layer.type() == "InnerProduct")
  521. {
  522. const caffe::LayerParameter& binlayer = net.layer(netidx);
  523. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  524. const caffe::InnerProductParameter& inner_product_param = layer.inner_product_param();
  525. fprintf(pp, " 0=%d", inner_product_param.num_output());
  526. fprintf(pp, " 1=%d", inner_product_param.bias_term());
  527. fprintf(pp, " 2=%d", weight_blob.data_size());
  528. for (int j=0; j<binlayer.blobs_size(); j++)
  529. {
  530. int quantize_tag = 0;
  531. const caffe::BlobProto& blob = binlayer.blobs(j);
  532. std::vector<float> quantize_table;
  533. std::vector<unsigned char> quantize_index;
  534. std::vector<unsigned short> float16_weights;
  535. // we will not quantize the bias values
  536. if (j == 0 && quantize_level != 0)
  537. {
  538. if (quantize_level == 256)
  539. {
  540. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  541. }
  542. else if (quantize_level == 65536)
  543. {
  544. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  545. }
  546. }
  547. // write quantize tag first
  548. if (j == 0)
  549. fwrite(&quantize_tag, sizeof(int), 1, bp);
  550. if (quantize_tag)
  551. {
  552. int p0 = ftell(bp);
  553. if (quantize_level == 256)
  554. {
  555. // write quantize table and index
  556. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  557. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  558. }
  559. else if (quantize_level == 65536)
  560. {
  561. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  562. }
  563. // padding to 32bit align
  564. int nwrite = ftell(bp) - p0;
  565. int nalign = alignSize(nwrite, 4);
  566. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  567. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  568. }
  569. else
  570. {
  571. // write original data
  572. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  573. }
  574. }
  575. }
  576. else if (layer.type() == "Input")
  577. {
  578. const caffe::InputParameter& input_param = layer.input_param();
  579. const caffe::BlobShape& bs = input_param.shape(0);
  580. for (int j=1; j<std::min((int)bs.dim_size(), 4); j++)
  581. {
  582. fprintf(pp, " %d=%ld", j-1, bs.dim(j));
  583. }
  584. for (int j=bs.dim_size(); j<4; j++)
  585. {
  586. fprintf(pp, " %d=-233", j-1);
  587. }
  588. }
  589. else if (layer.type() == "Interp")
  590. {
  591. const caffe::InterpParameter& interp_param = layer.interp_param();
  592. fprintf(pp, " 0=%d", 2);
  593. fprintf(pp, " 1=%f", (float)interp_param.zoom_factor());
  594. fprintf(pp, " 2=%f", (float)interp_param.zoom_factor());
  595. fprintf(pp, " 3=%d", interp_param.height());
  596. fprintf(pp, " 4=%d", interp_param.width());
  597. }
  598. else if (layer.type() == "LRN")
  599. {
  600. const caffe::LRNParameter& lrn_param = layer.lrn_param();
  601. fprintf(pp, " 0=%d", lrn_param.norm_region());
  602. fprintf(pp, " 1=%d", lrn_param.local_size());
  603. fprintf(pp, " 2=%f", lrn_param.alpha());
  604. fprintf(pp, " 3=%f", lrn_param.beta());
  605. }
  606. else if (layer.type() == "MemoryData")
  607. {
  608. const caffe::MemoryDataParameter& memory_data_param = layer.memory_data_param();
  609. fprintf(pp, " 0=%d", memory_data_param.width());
  610. fprintf(pp, " 1=%d", memory_data_param.height());
  611. fprintf(pp, " 2=%d", memory_data_param.channels());
  612. }
  613. else if (layer.type() == "Normalize")
  614. {
  615. const caffe::LayerParameter& binlayer = net.layer(netidx);
  616. const caffe::BlobProto& scale_blob = binlayer.blobs(0);
  617. const caffe::NormalizeParameter& norm_param = layer.norm_param();
  618. fprintf(pp, " 0=%d", norm_param.across_spatial());
  619. fprintf(pp, " 1=%d", norm_param.channel_shared());
  620. fprintf(pp, " 2=%f", norm_param.eps());
  621. fprintf(pp, " 3=%d", scale_blob.data_size());
  622. fwrite(scale_blob.data().data(), sizeof(float), scale_blob.data_size(), bp);
  623. }
  624. else if (layer.type() == "Permute")
  625. {
  626. const caffe::PermuteParameter& permute_param = layer.permute_param();
  627. int order_size = permute_param.order_size();
  628. int order_type = 0;
  629. if (order_size == 0)
  630. order_type = 0;
  631. if (order_size == 1)
  632. {
  633. int order0 = permute_param.order(0);
  634. if (order0 == 0)
  635. order_type = 0;
  636. // permute with N not supported
  637. }
  638. if (order_size == 2)
  639. {
  640. int order0 = permute_param.order(0);
  641. int order1 = permute_param.order(1);
  642. if (order0 == 0)
  643. {
  644. if (order1 == 1) // 0 1 2 3
  645. order_type = 0;
  646. else if (order1 == 2) // 0 2 1 3
  647. order_type = 2;
  648. else if (order1 == 3) // 0 3 1 2
  649. order_type = 4;
  650. }
  651. // permute with N not supported
  652. }
  653. if (order_size == 3 || order_size == 4)
  654. {
  655. int order0 = permute_param.order(0);
  656. int order1 = permute_param.order(1);
  657. int order2 = permute_param.order(2);
  658. if (order0 == 0)
  659. {
  660. if (order1 == 1)
  661. {
  662. if (order2 == 2) // 0 1 2 3
  663. order_type = 0;
  664. if (order2 == 3) // 0 1 3 2
  665. order_type = 1;
  666. }
  667. else if (order1 == 2)
  668. {
  669. if (order2 == 1) // 0 2 1 3
  670. order_type = 2;
  671. if (order2 == 3) // 0 2 3 1
  672. order_type = 3;
  673. }
  674. else if (order1 == 3)
  675. {
  676. if (order2 == 1) // 0 3 1 2
  677. order_type = 4;
  678. if (order2 == 2) // 0 3 2 1
  679. order_type = 5;
  680. }
  681. }
  682. // permute with N not supported
  683. }
  684. fprintf(pp, " 0=%d", order_type);
  685. }
  686. else if (layer.type() == "Pooling")
  687. {
  688. const caffe::PoolingParameter& pooling_param = layer.pooling_param();
  689. fprintf(pp, " 0=%d", pooling_param.pool());
  690. fprintf(pp, " 1=%d", pooling_param.kernel_size());
  691. fprintf(pp, " 2=%d", pooling_param.stride());
  692. fprintf(pp, " 3=%d", pooling_param.pad());
  693. fprintf(pp, " 4=%d", pooling_param.has_global_pooling() ? pooling_param.global_pooling() : 0);
  694. }
  695. else if (layer.type() == "Power")
  696. {
  697. const caffe::PowerParameter& power_param = layer.power_param();
  698. fprintf(pp, " 0=%f", power_param.power());
  699. fprintf(pp, " 1=%f", power_param.scale());
  700. fprintf(pp, " 2=%f", power_param.shift());
  701. }
  702. else if (layer.type() == "PReLU")
  703. {
  704. const caffe::LayerParameter& binlayer = net.layer(netidx);
  705. const caffe::BlobProto& slope_blob = binlayer.blobs(0);
  706. fprintf(pp, " 0=%d", slope_blob.data_size());
  707. fwrite(slope_blob.data().data(), sizeof(float), slope_blob.data_size(), bp);
  708. }
  709. else if (layer.type() == "PriorBox")
  710. {
  711. const caffe::PriorBoxParameter& prior_box_param = layer.prior_box_param();
  712. int num_aspect_ratio = prior_box_param.aspect_ratio_size();
  713. for (int j=0; j<prior_box_param.aspect_ratio_size(); j++)
  714. {
  715. float ar = prior_box_param.aspect_ratio(j);
  716. if (fabs(ar - 1.) < 1e-6) {
  717. num_aspect_ratio--;
  718. }
  719. }
  720. float variances[4] = {0.1f, 0.1f, 0.1f, 0.1f};
  721. if (prior_box_param.variance_size() == 4)
  722. {
  723. variances[0] = prior_box_param.variance(0);
  724. variances[1] = prior_box_param.variance(1);
  725. variances[2] = prior_box_param.variance(2);
  726. variances[3] = prior_box_param.variance(3);
  727. }
  728. else if (prior_box_param.variance_size() == 1)
  729. {
  730. variances[0] = prior_box_param.variance(0);
  731. variances[1] = prior_box_param.variance(0);
  732. variances[2] = prior_box_param.variance(0);
  733. variances[3] = prior_box_param.variance(0);
  734. }
  735. int flip = prior_box_param.has_flip() ? prior_box_param.flip() : 1;
  736. int clip = prior_box_param.has_clip() ? prior_box_param.clip() : 0;
  737. int image_width = -233;
  738. int image_height = -233;
  739. if (prior_box_param.has_img_size())
  740. {
  741. image_width = prior_box_param.img_size();
  742. image_height = prior_box_param.img_size();
  743. }
  744. else if (prior_box_param.has_img_w() && prior_box_param.has_img_h())
  745. {
  746. image_width = prior_box_param.img_w();
  747. image_height = prior_box_param.img_h();
  748. }
  749. float step_width = -233;
  750. float step_height = -233;
  751. if (prior_box_param.has_step())
  752. {
  753. step_width = prior_box_param.step();
  754. step_height = prior_box_param.step();
  755. }
  756. else if (prior_box_param.has_step_w() && prior_box_param.has_step_h())
  757. {
  758. step_width = prior_box_param.step_w();
  759. step_height = prior_box_param.step_h();
  760. }
  761. fprintf(pp, " -23300=%d", prior_box_param.min_size_size());
  762. for (int j=0; j<prior_box_param.min_size_size(); j++)
  763. {
  764. fprintf(pp, ",%f", prior_box_param.min_size(j));
  765. }
  766. fprintf(pp, " -23301=%d", prior_box_param.max_size_size());
  767. for (int j=0; j<prior_box_param.max_size_size(); j++)
  768. {
  769. fprintf(pp, ",%f", prior_box_param.max_size(j));
  770. }
  771. fprintf(pp, " -23302=%d", num_aspect_ratio);
  772. for (int j=0; j<prior_box_param.aspect_ratio_size(); j++)
  773. {
  774. float ar = prior_box_param.aspect_ratio(j);
  775. if (fabs(ar - 1.) < 1e-6) {
  776. continue;
  777. }
  778. fprintf(pp, ",%f", ar);
  779. }
  780. fprintf(pp, " 3=%f", variances[0]);
  781. fprintf(pp, " 4=%f", variances[1]);
  782. fprintf(pp, " 5=%f", variances[2]);
  783. fprintf(pp, " 6=%f", variances[3]);
  784. fprintf(pp, " 7=%d", flip);
  785. fprintf(pp, " 8=%d", clip);
  786. fprintf(pp, " 9=%d", image_width);
  787. fprintf(pp, " 10=%d", image_height);
  788. fprintf(pp, " 11=%f", step_width);
  789. fprintf(pp, " 12=%f", step_height);
  790. fprintf(pp, " 13=%f", prior_box_param.offset());
  791. }
  792. else if (layer.type() == "Python")
  793. {
  794. const caffe::PythonParameter& python_param = layer.python_param();
  795. std::string python_layer_name = python_param.layer();
  796. if (python_layer_name == "ProposalLayer")
  797. {
  798. int feat_stride = 16;
  799. sscanf(python_param.param_str().c_str(), "'feat_stride': %d", &feat_stride);
  800. int base_size = 16;
  801. // float ratio;
  802. // float scale;
  803. int pre_nms_topN = 6000;
  804. int after_nms_topN = 300;
  805. float nms_thresh = 0.7;
  806. int min_size = 16;
  807. fprintf(pp, " 0=%d", feat_stride);
  808. fprintf(pp, " 1=%d", base_size);
  809. fprintf(pp, " 2=%d", pre_nms_topN);
  810. fprintf(pp, " 3=%d", after_nms_topN);
  811. fprintf(pp, " 4=%f", nms_thresh);
  812. fprintf(pp, " 5=%d", min_size);
  813. }
  814. }
  815. else if (layer.type() == "ReLU")
  816. {
  817. const caffe::ReLUParameter& relu_param = layer.relu_param();
  818. fprintf(pp, " 0=%f", relu_param.negative_slope());
  819. }
  820. else if (layer.type() == "Reshape")
  821. {
  822. const caffe::ReshapeParameter& reshape_param = layer.reshape_param();
  823. const caffe::BlobShape& bs = reshape_param.shape();
  824. if (bs.dim_size() == 1)
  825. {
  826. fprintf(pp, " 0=%ld 1=-233 2=-233", bs.dim(0));
  827. }
  828. else if (bs.dim_size() == 2)
  829. {
  830. fprintf(pp, " 0=%ld 1=%ld 2=-233", bs.dim(1), bs.dim(0));
  831. }
  832. else if (bs.dim_size() == 3)
  833. {
  834. fprintf(pp, " 0=%ld 1=%ld 2=%ld", bs.dim(2), bs.dim(1), bs.dim(0));
  835. }
  836. else // bs.dim_size() == 4
  837. {
  838. fprintf(pp, " 0=%ld 1=%ld 2=%ld", bs.dim(3), bs.dim(2), bs.dim(1));
  839. }
  840. fprintf(pp, " 3=0");// permute
  841. }
  842. else if (layer.type() == "ROIPooling")
  843. {
  844. const caffe::ROIPoolingParameter& roi_pooling_param = layer.roi_pooling_param();
  845. fprintf(pp, " 0=%d", roi_pooling_param.pooled_w());
  846. fprintf(pp, " 1=%d", roi_pooling_param.pooled_h());
  847. fprintf(pp, " 2=%f", roi_pooling_param.spatial_scale());
  848. }
  849. else if (layer.type() == "Scale")
  850. {
  851. const caffe::LayerParameter& binlayer = net.layer(netidx);
  852. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  853. const caffe::ScaleParameter& scale_param = layer.scale_param();
  854. fprintf(pp, " 0=%d", (int)weight_blob.data_size());
  855. fprintf(pp, " 1=%d", scale_param.bias_term());
  856. for (int j=0; j<binlayer.blobs_size(); j++)
  857. {
  858. const caffe::BlobProto& blob = binlayer.blobs(j);
  859. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  860. }
  861. }
  862. else if (layer.type() == "Slice")
  863. {
  864. const caffe::SliceParameter& slice_param = layer.slice_param();
  865. if (slice_param.has_slice_dim())
  866. {
  867. int num_slice = layer.top_size();
  868. fprintf(pp, " -23300=%d", num_slice);
  869. for (int j=0; j<num_slice; j++)
  870. {
  871. fprintf(pp, ",-233");
  872. }
  873. }
  874. else
  875. {
  876. int num_slice = slice_param.slice_point_size() + 1;
  877. fprintf(pp, " -23300=%d", num_slice);
  878. int prev_offset = 0;
  879. for (int j=0; j<slice_param.slice_point_size(); j++)
  880. {
  881. int offset = slice_param.slice_point(j);
  882. fprintf(pp, ",%d", offset - prev_offset);
  883. prev_offset = offset;
  884. }
  885. fprintf(pp, ",-233");
  886. }
  887. }
  888. else if (layer.type() == "Softmax")
  889. {
  890. const caffe::SoftmaxParameter& softmax_param = layer.softmax_param();
  891. int dim = softmax_param.axis() - 1;
  892. fprintf(pp, " 0=%d", dim);
  893. }
  894. else if (layer.type() == "Threshold")
  895. {
  896. const caffe::ThresholdParameter& threshold_param = layer.threshold_param();
  897. fprintf(pp, " 0=%f", threshold_param.threshold());
  898. }
  899. fprintf(pp, "\n");
  900. // add split layer if top reference larger than one
  901. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  902. {
  903. std::string blob_name = blob_name_decorated[layer.top(0)];
  904. if (bottom_reference.find(blob_name) != bottom_reference.end())
  905. {
  906. int refcount = bottom_reference[blob_name];
  907. if (refcount > 1)
  908. {
  909. char splitname[256];
  910. sprintf(splitname, "splitncnn_%d", internal_split);
  911. fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount);
  912. fprintf(pp, " %s", blob_name.c_str());
  913. for (int j=0; j<refcount; j++)
  914. {
  915. fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j);
  916. }
  917. fprintf(pp, "\n");
  918. internal_split++;
  919. }
  920. }
  921. }
  922. else
  923. {
  924. for (int j=0; j<layer.top_size(); j++)
  925. {
  926. std::string blob_name = layer.top(j);
  927. if (bottom_reference.find(blob_name) != bottom_reference.end())
  928. {
  929. int refcount = bottom_reference[blob_name];
  930. if (refcount > 1)
  931. {
  932. char splitname[256];
  933. sprintf(splitname, "splitncnn_%d", internal_split);
  934. fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount);
  935. fprintf(pp, " %s", blob_name.c_str());
  936. for (int j=0; j<refcount; j++)
  937. {
  938. fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j);
  939. }
  940. fprintf(pp, "\n");
  941. internal_split++;
  942. }
  943. }
  944. }
  945. }
  946. }
  947. fclose(pp);
  948. fclose(bp);
  949. return 0;
  950. }