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

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