You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

caffe2ncnn.cpp 64 kB

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