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

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