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

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175
  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() == "ConvolutionDepthwise")
  280. {
  281. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  282. }
  283. else if (layer.type() == "Deconvolution")
  284. {
  285. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  286. if (convolution_param.group() != 1)
  287. fprintf(pp, "%-16s", "DeconvolutionDepthWise");
  288. else
  289. fprintf(pp, "%-16s", "Deconvolution");
  290. }
  291. else if (layer.type() == "MemoryData")
  292. {
  293. fprintf(pp, "%-16s", "Input");
  294. }
  295. else if (layer.type() == "Python")
  296. {
  297. const caffe::PythonParameter& python_param = layer.python_param();
  298. std::string python_layer_name = python_param.layer();
  299. if (python_layer_name == "ProposalLayer")
  300. fprintf(pp, "%-16s", "Proposal");
  301. else
  302. fprintf(pp, "%-16s", python_layer_name.c_str());
  303. }
  304. else
  305. {
  306. fprintf(pp, "%-16s", layer.type().c_str());
  307. }
  308. fprintf(pp, " %-16s %d %d", layer.name().c_str(), layer.bottom_size(), layer.top_size());
  309. for (int j=0; j<layer.bottom_size(); j++)
  310. {
  311. std::string blob_name = layer.bottom(j);
  312. if (blob_name_decorated.find(layer.bottom(j)) != blob_name_decorated.end())
  313. {
  314. blob_name = blob_name_decorated[layer.bottom(j)];
  315. }
  316. if (bottom_reference.find(blob_name) != bottom_reference.end())
  317. {
  318. int refidx = bottom_reference[blob_name] - 1;
  319. bottom_reference[blob_name] = refidx;
  320. char splitsuffix[256];
  321. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  322. blob_name = blob_name + splitsuffix;
  323. }
  324. fprintf(pp, " %s", blob_name.c_str());
  325. }
  326. // decorated
  327. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  328. {
  329. std::string blob_name = layer.top(0) + "_" + layer.name();
  330. blob_name_decorated[layer.top(0)] = blob_name;
  331. fprintf(pp, " %s", blob_name.c_str());
  332. }
  333. else
  334. {
  335. for (int j=0; j<layer.top_size(); j++)
  336. {
  337. std::string blob_name = layer.top(j);
  338. fprintf(pp, " %s", blob_name.c_str());
  339. }
  340. }
  341. // find blob binary by layer name
  342. int netidx;
  343. for (netidx=0; netidx<net.layer_size(); netidx++)
  344. {
  345. if (net.layer(netidx).name() == layer.name())
  346. {
  347. break;
  348. }
  349. }
  350. // layer specific params
  351. if (layer.type() == "BatchNorm")
  352. {
  353. const caffe::LayerParameter& binlayer = net.layer(netidx);
  354. const caffe::BlobProto& mean_blob = binlayer.blobs(0);
  355. const caffe::BlobProto& var_blob = binlayer.blobs(1);
  356. fprintf(pp, " 0=%d", (int)mean_blob.data_size());
  357. const caffe::BatchNormParameter& batch_norm_param = layer.batch_norm_param();
  358. float eps = batch_norm_param.eps();
  359. std::vector<float> ones(mean_blob.data_size(), 1.f);
  360. fwrite(ones.data(), sizeof(float), ones.size(), bp);// slope
  361. if (binlayer.blobs_size() < 3)
  362. {
  363. fwrite(mean_blob.data().data(), sizeof(float), mean_blob.data_size(), bp);
  364. float tmp;
  365. for (int j=0; j<var_blob.data_size(); j++)
  366. {
  367. tmp = var_blob.data().data()[j] + eps;
  368. fwrite(&tmp, sizeof(float), 1, bp);
  369. }
  370. }
  371. else
  372. {
  373. float scale_factor = 1 / binlayer.blobs(2).data().data()[0];
  374. // premultiply scale_factor to mean and variance
  375. float tmp;
  376. for (int j=0; j<mean_blob.data_size(); j++)
  377. {
  378. tmp = mean_blob.data().data()[j] * scale_factor;
  379. fwrite(&tmp, sizeof(float), 1, bp);
  380. }
  381. for (int j=0; j<var_blob.data_size(); j++)
  382. {
  383. tmp = var_blob.data().data()[j] * scale_factor + eps;
  384. fwrite(&tmp, sizeof(float), 1, bp);
  385. }
  386. }
  387. std::vector<float> zeros(mean_blob.data_size(), 0.f);
  388. fwrite(zeros.data(), sizeof(float), zeros.size(), bp);// bias
  389. }
  390. else if (layer.type() == "Concat")
  391. {
  392. const caffe::ConcatParameter& concat_param = layer.concat_param();
  393. int dim = concat_param.axis() - 1;
  394. fprintf(pp, " 0=%d", dim);
  395. }
  396. else if (layer.type() == "Convolution" || layer.type() == "ConvolutionDepthwise")
  397. {
  398. const caffe::LayerParameter& binlayer = net.layer(netidx);
  399. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  400. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  401. fprintf(pp, " 0=%d", convolution_param.num_output());
  402. if (convolution_param.has_kernel_w() && convolution_param.has_kernel_h())
  403. {
  404. fprintf(pp, " 1=%d", convolution_param.kernel_w());
  405. fprintf(pp, " 11=%d", convolution_param.kernel_h());
  406. }
  407. else
  408. {
  409. fprintf(pp, " 1=%d", convolution_param.kernel_size(0));
  410. }
  411. fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1);
  412. if (convolution_param.has_stride_w() && convolution_param.has_stride_h())
  413. {
  414. fprintf(pp, " 3=%d", convolution_param.stride_w());
  415. fprintf(pp, " 13=%d", convolution_param.stride_h());
  416. }
  417. else
  418. {
  419. fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1);
  420. }
  421. fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0);
  422. fprintf(pp, " 5=%d", convolution_param.bias_term());
  423. fprintf(pp, " 6=%d", weight_blob.data_size());
  424. if (layer.type() == "ConvolutionDepthwise")
  425. {
  426. fprintf(pp, " 7=%d", convolution_param.num_output());
  427. }
  428. else if (convolution_param.group() != 1)
  429. {
  430. fprintf(pp, " 7=%d", convolution_param.group());
  431. }
  432. for (int j = 0; j < binlayer.blobs_size(); j++)
  433. {
  434. int quantize_tag = 0;
  435. const caffe::BlobProto& blob = binlayer.blobs(j);
  436. std::vector<float> quantize_table;
  437. std::vector<unsigned char> quantize_index;
  438. std::vector<unsigned short> float16_weights;
  439. // we will not quantize the bias values
  440. if (j == 0 && quantize_level != 0)
  441. {
  442. if (quantize_level == 256)
  443. {
  444. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  445. }
  446. else if (quantize_level == 65536)
  447. {
  448. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  449. }
  450. }
  451. // write quantize tag first
  452. if (j == 0)
  453. fwrite(&quantize_tag, sizeof(int), 1, bp);
  454. if (quantize_tag)
  455. {
  456. int p0 = ftell(bp);
  457. if (quantize_level == 256)
  458. {
  459. // write quantize table and index
  460. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  461. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  462. }
  463. else if (quantize_level == 65536)
  464. {
  465. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  466. }
  467. // padding to 32bit align
  468. int nwrite = ftell(bp) - p0;
  469. int nalign = alignSize(nwrite, 4);
  470. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  471. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  472. }
  473. else
  474. {
  475. // write original data
  476. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  477. }
  478. }
  479. }
  480. else if (layer.type() == "Crop")
  481. {
  482. const caffe::CropParameter& crop_param = layer.crop_param();
  483. int num_offset = crop_param.offset_size();
  484. int woffset = (num_offset == 2) ? crop_param.offset(0) : 0;
  485. int hoffset = (num_offset == 2) ? crop_param.offset(1) : 0;
  486. fprintf(pp, " 0=%d", woffset);
  487. fprintf(pp, " 1=%d", hoffset);
  488. }
  489. else if (layer.type() == "Deconvolution")
  490. {
  491. const caffe::LayerParameter& binlayer = net.layer(netidx);
  492. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  493. const caffe::ConvolutionParameter& convolution_param = layer.convolution_param();
  494. fprintf(pp, " 0=%d", convolution_param.num_output());
  495. if (convolution_param.has_kernel_w() && convolution_param.has_kernel_h())
  496. {
  497. fprintf(pp, " 1=%d", convolution_param.kernel_w());
  498. fprintf(pp, " 11=%d", convolution_param.kernel_h());
  499. }
  500. else
  501. {
  502. fprintf(pp, " 1=%d", convolution_param.kernel_size(0));
  503. }
  504. fprintf(pp, " 2=%d", convolution_param.dilation_size() != 0 ? convolution_param.dilation(0) : 1);
  505. if (convolution_param.has_stride_w() && convolution_param.has_stride_h())
  506. {
  507. fprintf(pp, " 3=%d", convolution_param.stride_w());
  508. fprintf(pp, " 13=%d", convolution_param.stride_h());
  509. }
  510. else
  511. {
  512. fprintf(pp, " 3=%d", convolution_param.stride_size() != 0 ? convolution_param.stride(0) : 1);
  513. }
  514. fprintf(pp, " 4=%d", convolution_param.pad_size() != 0 ? convolution_param.pad(0) : 0);
  515. fprintf(pp, " 5=%d", convolution_param.bias_term());
  516. fprintf(pp, " 6=%d", weight_blob.data_size());
  517. if (convolution_param.group() != 1)
  518. {
  519. fprintf(pp, " 7=%d", convolution_param.group());
  520. }
  521. int quantized_weight = 0;
  522. fwrite(&quantized_weight, sizeof(int), 1, bp);
  523. // reorder weight from inch-outch to outch-inch
  524. int ksize = convolution_param.kernel_size(0);
  525. int num_output = convolution_param.num_output();
  526. int num_input = weight_blob.data_size() / (ksize * ksize) / num_output;
  527. const float* weight_data_ptr = weight_blob.data().data();
  528. for (int k=0; k<num_output; k++)
  529. {
  530. for (int j=0; j<num_input; j++)
  531. {
  532. fwrite(weight_data_ptr + (j*num_output + k) * ksize * ksize, sizeof(float), ksize * ksize, bp);
  533. }
  534. }
  535. for (int j=1; j<binlayer.blobs_size(); j++)
  536. {
  537. const caffe::BlobProto& blob = binlayer.blobs(j);
  538. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  539. }
  540. }
  541. else if (layer.type() == "DetectionOutput")
  542. {
  543. const caffe::DetectionOutputParameter& detection_output_param = layer.detection_output_param();
  544. const caffe::NonMaximumSuppressionParameter& nms_param = detection_output_param.nms_param();
  545. fprintf(pp, " 0=%d", detection_output_param.num_classes());
  546. fprintf(pp, " 1=%f", nms_param.nms_threshold());
  547. fprintf(pp, " 2=%d", nms_param.top_k());
  548. fprintf(pp, " 3=%d", detection_output_param.keep_top_k());
  549. fprintf(pp, " 4=%f", detection_output_param.confidence_threshold());
  550. }
  551. else if (layer.type() == "Dropout")
  552. {
  553. const caffe::DropoutParameter& dropout_param = layer.dropout_param();
  554. if (dropout_param.has_scale_train() && !dropout_param.scale_train())
  555. {
  556. float scale = 1.f - dropout_param.dropout_ratio();
  557. fprintf(pp, " 0=%f", scale);
  558. }
  559. }
  560. else if (layer.type() == "Eltwise")
  561. {
  562. const caffe::EltwiseParameter& eltwise_param = layer.eltwise_param();
  563. int coeff_size = eltwise_param.coeff_size();
  564. fprintf(pp, " 0=%d", (int)eltwise_param.operation());
  565. fprintf(pp, " -23301=%d", coeff_size);
  566. for (int j=0; j<coeff_size; j++)
  567. {
  568. fprintf(pp, ",%f", eltwise_param.coeff(j));
  569. }
  570. }
  571. else if (layer.type() == "ELU")
  572. {
  573. const caffe::ELUParameter& elu_param = layer.elu_param();
  574. fprintf(pp, " 0=%f", elu_param.alpha());
  575. }
  576. else if (layer.type() == "InnerProduct")
  577. {
  578. const caffe::LayerParameter& binlayer = net.layer(netidx);
  579. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  580. const caffe::InnerProductParameter& inner_product_param = layer.inner_product_param();
  581. fprintf(pp, " 0=%d", inner_product_param.num_output());
  582. fprintf(pp, " 1=%d", inner_product_param.bias_term());
  583. fprintf(pp, " 2=%d", weight_blob.data_size());
  584. for (int j=0; j<binlayer.blobs_size(); j++)
  585. {
  586. int quantize_tag = 0;
  587. const caffe::BlobProto& blob = binlayer.blobs(j);
  588. std::vector<float> quantize_table;
  589. std::vector<unsigned char> quantize_index;
  590. std::vector<unsigned short> float16_weights;
  591. // we will not quantize the bias values
  592. if (j == 0 && quantize_level != 0)
  593. {
  594. if (quantize_level == 256)
  595. {
  596. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), quantize_level, quantize_table, quantize_index);
  597. }
  598. else if (quantize_level == 65536)
  599. {
  600. quantize_tag = quantize_weight((float *)blob.data().data(), blob.data_size(), float16_weights);
  601. }
  602. }
  603. // write quantize tag first
  604. if (j == 0)
  605. fwrite(&quantize_tag, sizeof(int), 1, bp);
  606. if (quantize_tag)
  607. {
  608. int p0 = ftell(bp);
  609. if (quantize_level == 256)
  610. {
  611. // write quantize table and index
  612. fwrite(quantize_table.data(), sizeof(float), quantize_table.size(), bp);
  613. fwrite(quantize_index.data(), sizeof(unsigned char), quantize_index.size(), bp);
  614. }
  615. else if (quantize_level == 65536)
  616. {
  617. fwrite(float16_weights.data(), sizeof(unsigned short), float16_weights.size(), bp);
  618. }
  619. // padding to 32bit align
  620. int nwrite = ftell(bp) - p0;
  621. int nalign = alignSize(nwrite, 4);
  622. unsigned char padding[4] = {0x00, 0x00, 0x00, 0x00};
  623. fwrite(padding, sizeof(unsigned char), nalign - nwrite, bp);
  624. }
  625. else
  626. {
  627. // write original data
  628. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  629. }
  630. }
  631. }
  632. else if (layer.type() == "Input")
  633. {
  634. const caffe::InputParameter& input_param = layer.input_param();
  635. const caffe::BlobShape& bs = input_param.shape(0);
  636. if (bs.dim_size() == 4)
  637. {
  638. fprintf(pp, " 0=%ld", bs.dim(3));
  639. fprintf(pp, " 1=%ld", bs.dim(2));
  640. fprintf(pp, " 2=%ld", bs.dim(1));
  641. }
  642. else if (bs.dim_size() == 3)
  643. {
  644. fprintf(pp, " 0=%ld", bs.dim(2));
  645. fprintf(pp, " 1=%ld", bs.dim(1));
  646. fprintf(pp, " 2=-233");
  647. }
  648. else if (bs.dim_size() == 2)
  649. {
  650. fprintf(pp, " 0=%ld", bs.dim(1));
  651. fprintf(pp, " 1=-233");
  652. fprintf(pp, " 2=-233");
  653. }
  654. }
  655. else if (layer.type() == "Interp")
  656. {
  657. const caffe::InterpParameter& interp_param = layer.interp_param();
  658. fprintf(pp, " 0=%d", 2);
  659. fprintf(pp, " 1=%f", (float)interp_param.zoom_factor());
  660. fprintf(pp, " 2=%f", (float)interp_param.zoom_factor());
  661. fprintf(pp, " 3=%d", interp_param.height());
  662. fprintf(pp, " 4=%d", interp_param.width());
  663. }
  664. else if (layer.type() == "LRN")
  665. {
  666. const caffe::LRNParameter& lrn_param = layer.lrn_param();
  667. fprintf(pp, " 0=%d", lrn_param.norm_region());
  668. fprintf(pp, " 1=%d", lrn_param.local_size());
  669. fprintf(pp, " 2=%f", lrn_param.alpha());
  670. fprintf(pp, " 3=%f", lrn_param.beta());
  671. }
  672. else if (layer.type() == "MemoryData")
  673. {
  674. const caffe::MemoryDataParameter& memory_data_param = layer.memory_data_param();
  675. fprintf(pp, " 0=%d", memory_data_param.width());
  676. fprintf(pp, " 1=%d", memory_data_param.height());
  677. fprintf(pp, " 2=%d", memory_data_param.channels());
  678. }
  679. else if (layer.type() == "MVN")
  680. {
  681. const caffe::MVNParameter& mvn_param = layer.mvn_param();
  682. fprintf(pp, " 0=%d", mvn_param.normalize_variance());
  683. fprintf(pp, " 1=%d", mvn_param.across_channels());
  684. fprintf(pp, " 2=%f", mvn_param.eps());
  685. }
  686. else if (layer.type() == "Normalize")
  687. {
  688. const caffe::LayerParameter& binlayer = net.layer(netidx);
  689. const caffe::BlobProto& scale_blob = binlayer.blobs(0);
  690. const caffe::NormalizeParameter& norm_param = layer.norm_param();
  691. fprintf(pp, " 0=%d", norm_param.across_spatial());
  692. fprintf(pp, " 1=%d", norm_param.channel_shared());
  693. fprintf(pp, " 2=%f", norm_param.eps());
  694. fprintf(pp, " 3=%d", scale_blob.data_size());
  695. fwrite(scale_blob.data().data(), sizeof(float), scale_blob.data_size(), bp);
  696. }
  697. else if (layer.type() == "Permute")
  698. {
  699. const caffe::PermuteParameter& permute_param = layer.permute_param();
  700. int order_size = permute_param.order_size();
  701. int order_type = 0;
  702. if (order_size == 0)
  703. order_type = 0;
  704. if (order_size == 1)
  705. {
  706. int order0 = permute_param.order(0);
  707. if (order0 == 0)
  708. order_type = 0;
  709. // permute with N not supported
  710. }
  711. if (order_size == 2)
  712. {
  713. int order0 = permute_param.order(0);
  714. int order1 = permute_param.order(1);
  715. if (order0 == 0)
  716. {
  717. if (order1 == 1) // 0 1 2 3
  718. order_type = 0;
  719. else if (order1 == 2) // 0 2 1 3
  720. order_type = 2;
  721. else if (order1 == 3) // 0 3 1 2
  722. order_type = 4;
  723. }
  724. // permute with N not supported
  725. }
  726. if (order_size == 3 || order_size == 4)
  727. {
  728. int order0 = permute_param.order(0);
  729. int order1 = permute_param.order(1);
  730. int order2 = permute_param.order(2);
  731. if (order0 == 0)
  732. {
  733. if (order1 == 1)
  734. {
  735. if (order2 == 2) // 0 1 2 3
  736. order_type = 0;
  737. if (order2 == 3) // 0 1 3 2
  738. order_type = 1;
  739. }
  740. else if (order1 == 2)
  741. {
  742. if (order2 == 1) // 0 2 1 3
  743. order_type = 2;
  744. if (order2 == 3) // 0 2 3 1
  745. order_type = 3;
  746. }
  747. else if (order1 == 3)
  748. {
  749. if (order2 == 1) // 0 3 1 2
  750. order_type = 4;
  751. if (order2 == 2) // 0 3 2 1
  752. order_type = 5;
  753. }
  754. }
  755. // permute with N not supported
  756. }
  757. fprintf(pp, " 0=%d", order_type);
  758. }
  759. else if (layer.type() == "Pooling")
  760. {
  761. const caffe::PoolingParameter& pooling_param = layer.pooling_param();
  762. fprintf(pp, " 0=%d", pooling_param.pool());
  763. if (pooling_param.has_kernel_w() && pooling_param.has_kernel_h())
  764. {
  765. fprintf(pp, " 1=%d", pooling_param.kernel_w());
  766. fprintf(pp, " 11=%d", pooling_param.kernel_h());
  767. }
  768. else
  769. {
  770. fprintf(pp, " 1=%d", pooling_param.kernel_size());
  771. }
  772. if (pooling_param.has_stride_w() && pooling_param.has_stride_h())
  773. {
  774. fprintf(pp, " 2=%d", pooling_param.stride_w());
  775. fprintf(pp, " 12=%d", pooling_param.stride_h());
  776. }
  777. else
  778. {
  779. fprintf(pp, " 2=%d", pooling_param.stride());
  780. }
  781. if (pooling_param.has_pad_w() && pooling_param.has_pad_h())
  782. {
  783. fprintf(pp, " 3=%d", pooling_param.pad_w());
  784. fprintf(pp, " 13=%d", pooling_param.pad_h());
  785. }
  786. else
  787. {
  788. fprintf(pp, " 3=%d", pooling_param.pad());
  789. }
  790. fprintf(pp, " 4=%d", pooling_param.has_global_pooling() ? pooling_param.global_pooling() : 0);
  791. }
  792. else if (layer.type() == "Power")
  793. {
  794. const caffe::PowerParameter& power_param = layer.power_param();
  795. fprintf(pp, " 0=%f", power_param.power());
  796. fprintf(pp, " 1=%f", power_param.scale());
  797. fprintf(pp, " 2=%f", power_param.shift());
  798. }
  799. else if (layer.type() == "PReLU")
  800. {
  801. const caffe::LayerParameter& binlayer = net.layer(netidx);
  802. const caffe::BlobProto& slope_blob = binlayer.blobs(0);
  803. fprintf(pp, " 0=%d", slope_blob.data_size());
  804. fwrite(slope_blob.data().data(), sizeof(float), slope_blob.data_size(), bp);
  805. }
  806. else if (layer.type() == "PriorBox")
  807. {
  808. const caffe::PriorBoxParameter& prior_box_param = layer.prior_box_param();
  809. int num_aspect_ratio = prior_box_param.aspect_ratio_size();
  810. for (int j=0; j<prior_box_param.aspect_ratio_size(); j++)
  811. {
  812. float ar = prior_box_param.aspect_ratio(j);
  813. if (fabs(ar - 1.) < 1e-6) {
  814. num_aspect_ratio--;
  815. }
  816. }
  817. float variances[4] = {0.1f, 0.1f, 0.1f, 0.1f};
  818. if (prior_box_param.variance_size() == 4)
  819. {
  820. variances[0] = prior_box_param.variance(0);
  821. variances[1] = prior_box_param.variance(1);
  822. variances[2] = prior_box_param.variance(2);
  823. variances[3] = prior_box_param.variance(3);
  824. }
  825. else if (prior_box_param.variance_size() == 1)
  826. {
  827. variances[0] = prior_box_param.variance(0);
  828. variances[1] = prior_box_param.variance(0);
  829. variances[2] = prior_box_param.variance(0);
  830. variances[3] = prior_box_param.variance(0);
  831. }
  832. int flip = prior_box_param.has_flip() ? prior_box_param.flip() : 1;
  833. int clip = prior_box_param.has_clip() ? prior_box_param.clip() : 0;
  834. int image_width = -233;
  835. int image_height = -233;
  836. if (prior_box_param.has_img_size())
  837. {
  838. image_width = prior_box_param.img_size();
  839. image_height = prior_box_param.img_size();
  840. }
  841. else if (prior_box_param.has_img_w() && prior_box_param.has_img_h())
  842. {
  843. image_width = prior_box_param.img_w();
  844. image_height = prior_box_param.img_h();
  845. }
  846. float step_width = -233;
  847. float step_height = -233;
  848. if (prior_box_param.has_step())
  849. {
  850. step_width = prior_box_param.step();
  851. step_height = prior_box_param.step();
  852. }
  853. else if (prior_box_param.has_step_w() && prior_box_param.has_step_h())
  854. {
  855. step_width = prior_box_param.step_w();
  856. step_height = prior_box_param.step_h();
  857. }
  858. fprintf(pp, " -23300=%d", prior_box_param.min_size_size());
  859. for (int j=0; j<prior_box_param.min_size_size(); j++)
  860. {
  861. fprintf(pp, ",%f", prior_box_param.min_size(j));
  862. }
  863. fprintf(pp, " -23301=%d", prior_box_param.max_size_size());
  864. for (int j=0; j<prior_box_param.max_size_size(); j++)
  865. {
  866. fprintf(pp, ",%f", prior_box_param.max_size(j));
  867. }
  868. fprintf(pp, " -23302=%d", num_aspect_ratio);
  869. for (int j=0; j<prior_box_param.aspect_ratio_size(); j++)
  870. {
  871. float ar = prior_box_param.aspect_ratio(j);
  872. if (fabs(ar - 1.) < 1e-6) {
  873. continue;
  874. }
  875. fprintf(pp, ",%f", ar);
  876. }
  877. fprintf(pp, " 3=%f", variances[0]);
  878. fprintf(pp, " 4=%f", variances[1]);
  879. fprintf(pp, " 5=%f", variances[2]);
  880. fprintf(pp, " 6=%f", variances[3]);
  881. fprintf(pp, " 7=%d", flip);
  882. fprintf(pp, " 8=%d", clip);
  883. fprintf(pp, " 9=%d", image_width);
  884. fprintf(pp, " 10=%d", image_height);
  885. fprintf(pp, " 11=%f", step_width);
  886. fprintf(pp, " 12=%f", step_height);
  887. fprintf(pp, " 13=%f", prior_box_param.offset());
  888. }
  889. else if (layer.type() == "Python")
  890. {
  891. const caffe::PythonParameter& python_param = layer.python_param();
  892. std::string python_layer_name = python_param.layer();
  893. if (python_layer_name == "ProposalLayer")
  894. {
  895. int feat_stride = 16;
  896. sscanf(python_param.param_str().c_str(), "'feat_stride': %d", &feat_stride);
  897. int base_size = 16;
  898. // float ratio;
  899. // float scale;
  900. int pre_nms_topN = 6000;
  901. int after_nms_topN = 300;
  902. float nms_thresh = 0.7;
  903. int min_size = 16;
  904. fprintf(pp, " 0=%d", feat_stride);
  905. fprintf(pp, " 1=%d", base_size);
  906. fprintf(pp, " 2=%d", pre_nms_topN);
  907. fprintf(pp, " 3=%d", after_nms_topN);
  908. fprintf(pp, " 4=%f", nms_thresh);
  909. fprintf(pp, " 5=%d", min_size);
  910. }
  911. }
  912. else if (layer.type() == "ReLU")
  913. {
  914. const caffe::ReLUParameter& relu_param = layer.relu_param();
  915. if (relu_param.has_negative_slope())
  916. {
  917. fprintf(pp, " 0=%f", relu_param.negative_slope());
  918. }
  919. }
  920. else if (layer.type() == "Reshape")
  921. {
  922. const caffe::ReshapeParameter& reshape_param = layer.reshape_param();
  923. const caffe::BlobShape& bs = reshape_param.shape();
  924. if (bs.dim_size() == 1)
  925. {
  926. fprintf(pp, " 0=%ld 1=-233 2=-233", bs.dim(0));
  927. }
  928. else if (bs.dim_size() == 2)
  929. {
  930. fprintf(pp, " 0=%ld 1=%ld 2=-233", bs.dim(1), bs.dim(0));
  931. }
  932. else if (bs.dim_size() == 3)
  933. {
  934. fprintf(pp, " 0=%ld 1=%ld 2=%ld", bs.dim(2), bs.dim(1), bs.dim(0));
  935. }
  936. else // bs.dim_size() == 4
  937. {
  938. fprintf(pp, " 0=%ld 1=%ld 2=%ld", bs.dim(3), bs.dim(2), bs.dim(1));
  939. }
  940. fprintf(pp, " 3=0");// permute
  941. }
  942. else if (layer.type() == "ROIPooling")
  943. {
  944. const caffe::ROIPoolingParameter& roi_pooling_param = layer.roi_pooling_param();
  945. fprintf(pp, " 0=%d", roi_pooling_param.pooled_w());
  946. fprintf(pp, " 1=%d", roi_pooling_param.pooled_h());
  947. fprintf(pp, " 2=%f", roi_pooling_param.spatial_scale());
  948. }
  949. else if (layer.type() == "Scale")
  950. {
  951. const caffe::LayerParameter& binlayer = net.layer(netidx);
  952. const caffe::ScaleParameter& scale_param = layer.scale_param();
  953. bool scale_weight = scale_param.bias_term() ? (binlayer.blobs_size() == 2) : (binlayer.blobs_size() == 1);
  954. if (scale_weight)
  955. {
  956. const caffe::BlobProto& weight_blob = binlayer.blobs(0);
  957. fprintf(pp, " 0=%d", (int)weight_blob.data_size());
  958. }
  959. else
  960. {
  961. fprintf(pp, " 0=-233");
  962. }
  963. fprintf(pp, " 1=%d", scale_param.bias_term());
  964. for (int j=0; j<binlayer.blobs_size(); j++)
  965. {
  966. const caffe::BlobProto& blob = binlayer.blobs(j);
  967. fwrite(blob.data().data(), sizeof(float), blob.data_size(), bp);
  968. }
  969. }
  970. else if (layer.type() == "ShuffleChannel")
  971. {
  972. const caffe::ShuffleChannelParameter&
  973. shuffle_channel_param = layer.shuffle_channel_param();
  974. fprintf(pp, " 0=%d", shuffle_channel_param.group());
  975. }
  976. else if (layer.type() == "Slice")
  977. {
  978. const caffe::SliceParameter& slice_param = layer.slice_param();
  979. if (slice_param.has_slice_dim())
  980. {
  981. int num_slice = layer.top_size();
  982. fprintf(pp, " -23300=%d", num_slice);
  983. for (int j=0; j<num_slice; j++)
  984. {
  985. fprintf(pp, ",-233");
  986. }
  987. }
  988. else
  989. {
  990. int num_slice = slice_param.slice_point_size() + 1;
  991. fprintf(pp, " -23300=%d", num_slice);
  992. int prev_offset = 0;
  993. for (int j=0; j<slice_param.slice_point_size(); j++)
  994. {
  995. int offset = slice_param.slice_point(j);
  996. fprintf(pp, ",%d", offset - prev_offset);
  997. prev_offset = offset;
  998. }
  999. fprintf(pp, ",-233");
  1000. }
  1001. int dim = slice_param.axis() - 1;
  1002. fprintf(pp, " 1=%d", dim);
  1003. }
  1004. else if (layer.type() == "Softmax")
  1005. {
  1006. const caffe::SoftmaxParameter& softmax_param = layer.softmax_param();
  1007. int dim = softmax_param.axis() - 1;
  1008. fprintf(pp, " 0=%d", dim);
  1009. }
  1010. else if (layer.type() == "Threshold")
  1011. {
  1012. const caffe::ThresholdParameter& threshold_param = layer.threshold_param();
  1013. fprintf(pp, " 0=%f", threshold_param.threshold());
  1014. }
  1015. fprintf(pp, "\n");
  1016. // add split layer if top reference larger than one
  1017. if (layer.bottom_size() == 1 && layer.top_size() == 1 && layer.bottom(0) == layer.top(0))
  1018. {
  1019. std::string blob_name = blob_name_decorated[layer.top(0)];
  1020. if (bottom_reference.find(blob_name) != bottom_reference.end())
  1021. {
  1022. int refcount = bottom_reference[blob_name];
  1023. if (refcount > 1)
  1024. {
  1025. char splitname[256];
  1026. sprintf(splitname, "splitncnn_%d", internal_split);
  1027. fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount);
  1028. fprintf(pp, " %s", blob_name.c_str());
  1029. for (int j=0; j<refcount; j++)
  1030. {
  1031. fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j);
  1032. }
  1033. fprintf(pp, "\n");
  1034. internal_split++;
  1035. }
  1036. }
  1037. }
  1038. else
  1039. {
  1040. for (int j=0; j<layer.top_size(); j++)
  1041. {
  1042. std::string blob_name = layer.top(j);
  1043. if (bottom_reference.find(blob_name) != bottom_reference.end())
  1044. {
  1045. int refcount = bottom_reference[blob_name];
  1046. if (refcount > 1)
  1047. {
  1048. char splitname[256];
  1049. sprintf(splitname, "splitncnn_%d", internal_split);
  1050. fprintf(pp, "%-16s %-16s %d %d", "Split", splitname, 1, refcount);
  1051. fprintf(pp, " %s", blob_name.c_str());
  1052. for (int j=0; j<refcount; j++)
  1053. {
  1054. fprintf(pp, " %s_splitncnn_%d", blob_name.c_str(), j);
  1055. }
  1056. fprintf(pp, "\n");
  1057. internal_split++;
  1058. }
  1059. }
  1060. }
  1061. }
  1062. }
  1063. fclose(pp);
  1064. fclose(bp);
  1065. return 0;
  1066. }