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.

mxnet2ncnn.cpp 33 kB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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 <stdint.h>
  16. #include <string.h>
  17. #include <map>
  18. #include <set>
  19. #include <string>
  20. #include <vector>
  21. class MXNetParam;
  22. class MXNetNode
  23. {
  24. public:
  25. bool has_attr(const char* key) const;
  26. class AttrProxy
  27. {
  28. MXNetNode const* _n;
  29. const char* const _key;
  30. public:
  31. AttrProxy( MXNetNode const* n, const char* key ) : _n(n), _key(key) {}
  32. operator int() const { return _n->attr_i(_key); }
  33. operator float() const { return _n->attr_f(_key); }
  34. operator std::string() const { return _n->attr_s(_key); }
  35. operator std::vector<int>() const { return _n->attr_ai(_key); }
  36. };
  37. AttrProxy attr(const char* key) const { return AttrProxy(this, key); }
  38. int attr_i(const char* key) const;
  39. float attr_f(const char* key) const;
  40. std::string attr_s(const char* key) const;
  41. std::vector<int> attr_ai(const char* key) const;
  42. public:
  43. bool is_weight() const;
  44. bool has_weight(int i) const;
  45. std::vector<float> weight(int i, int init_len = 0) const;
  46. std::vector<MXNetNode>* nodes;// reference
  47. std::vector<MXNetParam>* params;// reference
  48. public:
  49. std::string op;
  50. std::string name;
  51. std::map<std::string, std::string> attrs;
  52. std::vector<int> inputs;
  53. std::vector<int> subinputs;
  54. std::vector<int> weights;
  55. };
  56. class MXNetParam
  57. {
  58. public:
  59. std::string name;
  60. std::vector<float> data;
  61. std::string init;
  62. };
  63. bool MXNetNode::has_attr(const char* key) const
  64. {
  65. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  66. return it != attrs.end();
  67. }
  68. int MXNetNode::attr_i(const char* key) const
  69. {
  70. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  71. if (it == attrs.end())
  72. return 0;
  73. if (it->second == "False")
  74. return 0;
  75. if (it->second == "True")
  76. return 1;
  77. int i = 0;
  78. int nscan = sscanf(it->second.c_str(), "%d", &i);
  79. if (nscan != 1)
  80. return 0;
  81. return i;
  82. }
  83. float MXNetNode::attr_f(const char* key) const
  84. {
  85. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  86. if (it == attrs.end())
  87. return 0.f;
  88. float f = 0;
  89. int nscan = sscanf(it->second.c_str(), "%f", &f);
  90. if (nscan != 1)
  91. return 0.f;
  92. return f;
  93. }
  94. std::string MXNetNode::attr_s(const char* key) const
  95. {
  96. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  97. if (it == attrs.end())
  98. return std::string();
  99. return it->second;
  100. }
  101. std::vector<int> MXNetNode::attr_ai(const char* key) const
  102. {
  103. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  104. if (it == attrs.end())
  105. return std::vector<int>();
  106. // (1,2,3)
  107. std::vector<int> list;
  108. int i = 0;
  109. int c = 0;
  110. int nconsumed = 0;
  111. int nscan = sscanf(it->second.c_str() + c, "%*[(,]%d%n", &i, &nconsumed);
  112. while (nscan == 1)
  113. {
  114. list.push_back(i);
  115. // fprintf(stderr, "%d\n", i);
  116. i = 0;
  117. c += nconsumed;
  118. nscan = sscanf(it->second.c_str() + c, "%*[(,]%d%n", &i, &nconsumed);
  119. }
  120. return list;
  121. }
  122. bool MXNetNode::is_weight() const
  123. {
  124. for (int i=0; i<(int)(*params).size(); i++)
  125. {
  126. const MXNetParam& p = (*params)[i];
  127. if (p.name == name)
  128. return true;
  129. }
  130. return false;
  131. }
  132. bool MXNetNode::has_weight(int i) const
  133. {
  134. if (i < 0 || i >= (int)weights.size())
  135. return false;
  136. const std::string& name = (*nodes)[ weights[i] ].name;
  137. for (int i=0; i<(int)(*params).size(); i++)
  138. {
  139. const MXNetParam& p = (*params)[i];
  140. if (p.name == name)
  141. return true;
  142. }
  143. return false;
  144. }
  145. std::vector<float> MXNetNode::weight(int i, int init_len) const
  146. {
  147. if (i < 0 || i >= (int)weights.size())
  148. return std::vector<float>();
  149. const std::string& name = (*nodes)[ weights[i] ].name;
  150. for (int i=0; i<(int)(*params).size(); i++)
  151. {
  152. const MXNetParam& p = (*params)[i];
  153. if (p.name != name)
  154. continue;
  155. if (!p.data.empty())
  156. return p.data;
  157. std::vector<float> data;
  158. if (!p.init.empty() && init_len != 0)
  159. {
  160. if (p.init == "[\\$zero\\$, {}]")
  161. {
  162. data.resize(init_len, 0.f);
  163. }
  164. else if (p.init == "[\\$one\\$, {}]")
  165. {
  166. data.resize(init_len, 1.f);
  167. }
  168. }
  169. return data;
  170. }
  171. return std::vector<float>();
  172. }
  173. static void replace_backslash_doublequote_dollar(char* s)
  174. {
  175. char* a = s;
  176. char* b = s+1;
  177. while (*a && *b)
  178. {
  179. if (*a == '\\' && *b == '\"')
  180. {
  181. *b = '$';
  182. }
  183. a++;
  184. b++;
  185. }
  186. }
  187. static void parse_input_list(const char* s, std::vector<int>& inputs, std::vector<int>& subinputs)
  188. {
  189. inputs.clear();
  190. subinputs.clear();
  191. if (memcmp(s, "[]", 2) == 0)
  192. return;
  193. int nscan = 0;
  194. int nconsumed = 0;
  195. int id;
  196. int subid;
  197. int c = 1;// skip leading [
  198. nscan = sscanf(s + c, "[%d, %d%n", &id, &subid, &nconsumed);
  199. while (nscan == 2)
  200. {
  201. inputs.push_back(id);
  202. subinputs.push_back(subid);
  203. // fprintf(stderr, "%d %d\n", id, subid);
  204. c += nconsumed;
  205. nscan = sscanf(s + c, "%*[^[][%d, %d%n", &id, &subid, &nconsumed);
  206. }
  207. }
  208. static bool read_mxnet_json(const char* jsonpath, std::vector<MXNetNode>& nodes)
  209. {
  210. FILE* fp = fopen(jsonpath, "rb");
  211. if (!fp)
  212. {
  213. fprintf(stderr, "fopen %s failed\n", jsonpath);
  214. return false;
  215. }
  216. int internal_unknown = 0;
  217. char line[1024];
  218. //{
  219. fgets(line, 1024, fp);
  220. MXNetNode n;
  221. bool in_nodes_list = false;
  222. bool in_node_block = false;
  223. bool in_attr_block = false;
  224. while (!feof(fp))
  225. {
  226. char* s = fgets(line, 1024, fp);
  227. if (!s)
  228. break;
  229. if (in_attr_block)
  230. {
  231. // },
  232. if (memcmp(line, " }", 7) == 0)
  233. {
  234. in_attr_block = false;
  235. continue;
  236. }
  237. // replace \" with \$
  238. replace_backslash_doublequote_dollar(line);
  239. // "kernel": "(7,7)",
  240. char key[256] = {0};
  241. char value[256] = {0};
  242. int nscan = sscanf(line, " \"%255[^\"]\": \"%255[^\"]\"", key, value);
  243. if (nscan == 2)
  244. {
  245. n.attrs[key] = value;
  246. // fprintf(stderr, "# %s = %s\n", key, value);
  247. continue;
  248. }
  249. }
  250. if (in_node_block)
  251. {
  252. // },
  253. if (memcmp(line, " }", 5) == 0)
  254. {
  255. // new node
  256. if (n.name.empty())
  257. {
  258. // assign default unknown name
  259. char unknownname[256];
  260. sprintf(unknownname, "unknownncnn_%d", internal_unknown);
  261. n.name = unknownname;
  262. internal_unknown++;
  263. }
  264. nodes.push_back(n);
  265. in_node_block = false;
  266. continue;
  267. }
  268. int nscan;
  269. // "op": "Convolution",
  270. char op[256] = {0};
  271. nscan = sscanf(line, " \"op\": \"%255[^\"]\",", op);
  272. if (nscan == 1)
  273. {
  274. n.op = op;
  275. // fprintf(stderr, "op = %s\n", op);
  276. continue;
  277. }
  278. // "name": "conv0",
  279. char name[256] = {0};
  280. nscan = sscanf(line, " \"name\": \"%255[^\"]\",", name);
  281. if (nscan == 1)
  282. {
  283. n.name = name;
  284. // fprintf(stderr, "name = %s\n", name);
  285. continue;
  286. }
  287. // "inputs": []
  288. char inputs[256] = {0};
  289. nscan = sscanf(line, " \"inputs\": %255[^\n]", inputs);
  290. if (nscan == 1)
  291. {
  292. parse_input_list(inputs, n.inputs, n.subinputs);
  293. // fprintf(stderr, "inputs = %s\n", inputs);
  294. continue;
  295. }
  296. // "param": {},
  297. if (memcmp(line, " \"param\": {}", 17) == 0)
  298. {
  299. continue;
  300. }
  301. // replace \" with \$
  302. replace_backslash_doublequote_dollar(line);
  303. // "attr": {"__init__": "[\"zero\", {}]"},
  304. char key[256] = {0};
  305. char value[256] = {0};
  306. nscan = sscanf(line, " \"attr\": {\"%255[^\"]\": \"%255[^\"]\"}", key, value);
  307. if (nscan == 2)
  308. {
  309. n.attrs[key] = value;
  310. // fprintf(stderr, "# %s = %s\n", key, value);
  311. continue;
  312. }
  313. // "attrs": {"__init__": "[\"zero\", {}]"},
  314. nscan = sscanf(line, " \"attrs\": {\"%255[^\"]\": \"%255[^\"]\"}", key, value);
  315. if (nscan == 2)
  316. {
  317. n.attrs[key] = value;
  318. // fprintf(stderr, "# %s = %s\n", key, value);
  319. continue;
  320. }
  321. // "param": {"p": "0.5"},
  322. nscan = sscanf(line, " \"param\": {\"%255[^\"]\": \"%255[^\"]\"}", key, value);
  323. if (nscan == 2)
  324. {
  325. n.attrs[key] = value;
  326. // fprintf(stderr, "# %s = %s\n", key, value);
  327. continue;
  328. }
  329. // "attr": {
  330. if (memcmp(line, " \"attr\": {", 15) == 0)
  331. {
  332. in_attr_block = true;
  333. continue;
  334. }
  335. // "attrs": {
  336. if (memcmp(line, " \"attrs\": {", 15) == 0)
  337. {
  338. in_attr_block = true;
  339. continue;
  340. }
  341. // "param": {
  342. if (memcmp(line, " \"param\": {", 16) == 0)
  343. {
  344. in_attr_block = true;
  345. continue;
  346. }
  347. }
  348. if (in_nodes_list)
  349. {
  350. // ],
  351. if (memcmp(line, " ],", 4) == 0)
  352. {
  353. in_nodes_list = false;
  354. // all nodes parsed
  355. break;
  356. }
  357. // {
  358. if (memcmp(line, " {", 5) == 0)
  359. {
  360. n = MXNetNode();
  361. in_node_block = true;
  362. continue;
  363. }
  364. }
  365. // "nodes": [
  366. if (memcmp(line, " \"nodes\": [", 12) == 0)
  367. {
  368. in_nodes_list = true;
  369. continue;
  370. }
  371. }
  372. fclose(fp);
  373. return true;
  374. }
  375. static bool read_mxnet_param(const char* parampath, std::vector<MXNetParam>& params)
  376. {
  377. FILE* fp = fopen(parampath, "rb");
  378. if (!fp)
  379. {
  380. fprintf(stderr, "fopen %s failed\n", parampath);
  381. return false;
  382. }
  383. uint64_t header;
  384. uint64_t reserved;
  385. fread(&header, 1, sizeof(uint64_t), fp);
  386. fread(&reserved, 1, sizeof(uint64_t), fp);
  387. // NDArray vec
  388. // each data
  389. uint64_t data_count;
  390. fread(&data_count, 1, sizeof(uint64_t), fp);
  391. // fprintf(stderr, "data count = %d\n", (int)data_count);
  392. for (int i = 0; i < (int)data_count; i++)
  393. {
  394. uint32_t magic;// 0xF993FAC9
  395. fread(&magic, 1, sizeof(uint32_t), fp);
  396. // shape
  397. uint32_t ndim;
  398. std::vector<int64_t> shape;
  399. if (magic == 0xF993FAC9)
  400. {
  401. int32_t stype;
  402. fread(&stype, 1, sizeof(int32_t), fp);
  403. fread(&ndim, 1, sizeof(uint32_t), fp);
  404. shape.resize(ndim);
  405. fread(&shape[0], 1, ndim * sizeof(int64_t), fp);
  406. }
  407. else if (magic == 0xF993FAC8)
  408. {
  409. fread(&ndim, 1, sizeof(uint32_t), fp);
  410. shape.resize(ndim);
  411. fread(&shape[0], 1, ndim * sizeof(int64_t), fp);
  412. }
  413. else
  414. {
  415. ndim = magic;
  416. shape.resize(ndim);
  417. std::vector<uint32_t> shape32;
  418. shape32.resize(ndim);
  419. fread(&shape32[0], 1, ndim * sizeof(uint32_t), fp);
  420. for (int j=0; j<(int)ndim; j++)
  421. {
  422. shape[j] = shape32[j];
  423. }
  424. }
  425. // context
  426. int32_t dev_type;
  427. int32_t dev_id;
  428. fread(&dev_type, 1, sizeof(int32_t), fp);
  429. fread(&dev_id, 1, sizeof(int32_t), fp);
  430. int32_t type_flag;
  431. fread(&type_flag, 1, sizeof(int32_t), fp);
  432. // data
  433. size_t len = 0;
  434. if (shape.size() == 1) len = shape[0];
  435. if (shape.size() == 2) len = shape[0] * shape[1];
  436. if (shape.size() == 3) len = shape[0] * shape[1] * shape[2];
  437. if (shape.size() == 4) len = shape[0] * shape[1] * shape[2] * shape[3];
  438. MXNetParam p;
  439. p.data.resize(len);
  440. fread(&p.data[0], 1, len * sizeof(float), fp);
  441. params.push_back(p);
  442. // fprintf(stderr, "%u read\n", len);
  443. }
  444. // each name
  445. uint64_t name_count;
  446. fread(&name_count, 1, sizeof(uint64_t), fp);
  447. // fprintf(stderr, "name count = %d\n", (int)name_count);
  448. for (int i = 0; i < (int)name_count; i++)
  449. {
  450. uint64_t len;
  451. fread(&len, 1, sizeof(uint64_t), fp);
  452. MXNetParam& p = params[i];
  453. p.name.resize(len);
  454. fread((char*)p.name.data(), 1, len, fp);
  455. // cut leading arg:
  456. if (memcmp(p.name.c_str(), "arg:", 4) == 0)
  457. {
  458. p.name = std::string(p.name.c_str() + 4);
  459. }
  460. if (memcmp(p.name.c_str(), "aux:", 4) == 0)
  461. {
  462. p.name = std::string(p.name.c_str() + 4);
  463. }
  464. // fprintf(stderr, "%s read\n", p.name.c_str());
  465. }
  466. fclose(fp);
  467. return true;
  468. }
  469. int main(int argc, char** argv)
  470. {
  471. const char* jsonpath = argv[1];
  472. const char* parampath = argv[2];
  473. const char* ncnn_prototxt = argc >= 5 ? argv[3] : "ncnn.param";
  474. const char* ncnn_modelbin = argc >= 5 ? argv[4] : "ncnn.bin";
  475. std::vector<MXNetNode> nodes;
  476. std::vector<MXNetParam> params;
  477. read_mxnet_json(jsonpath, nodes);
  478. read_mxnet_param(parampath, params);
  479. FILE* pp = fopen(ncnn_prototxt, "wb");
  480. FILE* bp = fopen(ncnn_modelbin, "wb");
  481. // magic
  482. fprintf(pp, "7767517\n");
  483. int node_count = nodes.size();
  484. // node reference
  485. std::map<int, int> node_reference;
  486. // weight node
  487. std::vector<int> weight_nodes;
  488. // global definition line
  489. // [layer count] [blob count]
  490. std::set<std::string> blob_names;
  491. for (int i=0; i<node_count; i++)
  492. {
  493. MXNetNode& n = nodes[i];
  494. // assign global param reference
  495. n.nodes = &nodes;
  496. n.params = &params;
  497. const std::string& output_name = n.name;
  498. int output_size = 1;
  499. if (n.op == "null")
  500. {
  501. if (n.is_weight())
  502. {
  503. weight_nodes.push_back(i);
  504. }
  505. else
  506. {
  507. if (n.has_attr("__init__"))
  508. {
  509. // init weight param
  510. MXNetParam pi;
  511. pi.name = n.name;
  512. pi.init = (std::string)n.attr("__init__");
  513. params.push_back(pi);
  514. weight_nodes.push_back(i);
  515. }
  516. else
  517. {
  518. // null node without data, treat it as network input
  519. }
  520. }
  521. continue;
  522. }
  523. else if (n.op == "SliceChannel")
  524. {
  525. output_size = n.attr("num_outputs");
  526. }
  527. // distinguish weights and inputs
  528. std::vector<int> weights;
  529. std::vector<int> inputs;
  530. for (int j=0; j<(int)n.inputs.size(); j++)
  531. {
  532. int input_index = n.inputs[j];
  533. if (nodes[input_index].is_weight())
  534. {
  535. weights.push_back(input_index);
  536. continue;
  537. }
  538. inputs.push_back(input_index);
  539. }
  540. n.inputs = inputs;
  541. n.weights = weights;
  542. // input
  543. for (int j=0; j<(int)n.inputs.size(); j++)
  544. {
  545. int input_index = n.inputs[j];
  546. int subinput_index = n.subinputs[j];
  547. std::string input_name = nodes[input_index].name;
  548. // fprintf(stderr, "input = %s\n", input_name.c_str());
  549. if (subinput_index != 0)
  550. {
  551. char subinputsuffix[256];
  552. sprintf(subinputsuffix, "_subncnn_%d", subinput_index);
  553. input_name = input_name + subinputsuffix;
  554. }
  555. blob_names.insert(input_name);
  556. int input_uid = input_index | (subinput_index << 16);
  557. if (node_reference.find(input_uid) == node_reference.end())
  558. {
  559. node_reference[input_uid] = 1;
  560. }
  561. else
  562. {
  563. node_reference[input_uid] = node_reference[input_uid] + 1;
  564. }
  565. }
  566. // output
  567. // fprintf(stderr, "output = %s\n", output_name.c_str());
  568. blob_names.insert(output_name);
  569. for (int j=1; j<output_size; j++)
  570. {
  571. char subinputsuffix[256];
  572. sprintf(subinputsuffix, "_%d", j);
  573. std::string output_name_j = output_name + subinputsuffix;
  574. blob_names.insert(output_name_j);
  575. }
  576. }
  577. // remove node_reference entry with reference equals to one
  578. int splitncnn_blob_count = 0;
  579. std::map<int, int>::iterator it = node_reference.begin();
  580. while (it != node_reference.end())
  581. {
  582. if (it->second == 1)
  583. {
  584. node_reference.erase(it++);
  585. }
  586. else
  587. {
  588. splitncnn_blob_count += it->second;
  589. // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second);
  590. ++it;
  591. }
  592. }
  593. fprintf(pp, "%lu %lu\n", node_count + node_reference.size() - weight_nodes.size(), blob_names.size() + splitncnn_blob_count);
  594. int internal_split = 0;
  595. for (int i=0; i<node_count; i++)
  596. {
  597. const MXNetNode& n = nodes[i];
  598. int output_size = 1;
  599. if (n.op == "null")
  600. {
  601. if (n.is_weight())
  602. {
  603. continue;
  604. }
  605. fprintf(pp, "%-16s", "Input");
  606. }
  607. else if (n.op == "Activation")
  608. {
  609. std::string type = n.attr("act_type");
  610. if (type == "relu")
  611. {
  612. fprintf(pp, "%-16s", "ReLU");
  613. }
  614. else if (type == "sigmoid")
  615. {
  616. fprintf(pp, "%-16s", "Sigmoid");
  617. }
  618. else if (type == "tanh")
  619. {
  620. fprintf(pp, "%-16s", "TanH");
  621. }
  622. }
  623. else if (n.op == "BatchNorm")
  624. {
  625. fprintf(pp, "%-16s", "BatchNorm");
  626. }
  627. else if (n.op == "Concat")
  628. {
  629. fprintf(pp, "%-16s", "Concat");
  630. }
  631. else if (n.op == "Convolution")
  632. {
  633. int num_group = n.attr("num_group");
  634. if (num_group > 1) {
  635. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  636. } else {
  637. fprintf(pp, "%-16s", "Convolution");
  638. }
  639. }
  640. else if (n.op == "Dropout")
  641. {
  642. fprintf(pp, "%-16s", "Dropout");
  643. }
  644. else if (n.op == "elemwise_add")
  645. {
  646. fprintf(pp, "%-16s", "BinaryOp");
  647. }
  648. else if (n.op == "elemwise_mul")
  649. {
  650. fprintf(pp, "%-16s", "BinaryOp");
  651. }
  652. else if (n.op == "Embedding")
  653. {
  654. fprintf(pp, "%-16s", "Embed");
  655. }
  656. else if (n.op == "Flatten")
  657. {
  658. fprintf(pp, "%-16s", "Flatten");
  659. }
  660. else if (n.op == "FullyConnected")
  661. {
  662. fprintf(pp, "%-16s", "InnerProduct");
  663. }
  664. else if (n.op == "LeakyReLU")
  665. {
  666. std::string type = n.attr("act_type");
  667. if (type == "elu")
  668. {
  669. fprintf(pp, "%-16s", "ELU");
  670. }
  671. else if (type == "leaky")
  672. {
  673. fprintf(pp, "%-16s", "ReLU");
  674. }
  675. else if (type == "prelu")
  676. {
  677. fprintf(pp, "%-16s", "PReLU");
  678. }
  679. }
  680. else if (n.op == "Pooling")
  681. {
  682. fprintf(pp, "%-16s", "Pooling");
  683. }
  684. else if (n.op == "SliceChannel")
  685. {
  686. fprintf(pp, "%-16s", "Slice");
  687. output_size = n.attr("num_outputs");
  688. }
  689. else if (n.op == "SoftmaxOutput")
  690. {
  691. fprintf(pp, "%-16s", "Softmax");
  692. }
  693. else if (n.op == "SoftmaxActivation")
  694. {
  695. fprintf(pp, "%-16s", "Softmax");
  696. }
  697. else
  698. {
  699. fprintf(stderr, "%s not supported yet!\n", n.op.c_str());
  700. fprintf(pp, "%-16s", n.op.c_str());
  701. }
  702. int input_size = n.inputs.size();
  703. for (int j=0; j<(int)n.inputs.size(); j++)
  704. {
  705. int input_index = n.inputs[j];
  706. if (nodes[input_index].is_weight())
  707. {
  708. input_size--;
  709. }
  710. }
  711. if (n.op == "SoftmaxOutput")
  712. {
  713. // drop label
  714. input_size--;
  715. }
  716. fprintf(pp, " %-32s %d %d", n.name.c_str(), input_size, output_size);
  717. for (int j=0; j<(int)n.inputs.size(); j++)
  718. {
  719. int input_index = n.inputs[j];
  720. int subinput_index = n.subinputs[j];
  721. if (nodes[input_index].is_weight())
  722. {
  723. continue;
  724. }
  725. if (n.op == "SoftmaxOutput")
  726. {
  727. // drop label
  728. if (j == 1)
  729. continue;
  730. }
  731. std::string input_name = nodes[input_index].name;
  732. if (subinput_index != 0)
  733. {
  734. char subinputsuffix[256];
  735. sprintf(subinputsuffix, "_subncnn_%d", subinput_index);
  736. input_name = input_name + subinputsuffix;
  737. }
  738. int input_uid = input_index | (subinput_index << 16);
  739. if (node_reference.find(input_uid) != node_reference.end())
  740. {
  741. int refidx = node_reference[input_uid] - 1;
  742. node_reference[input_uid] = refidx;
  743. char splitsuffix[256];
  744. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  745. input_name = input_name + splitsuffix;
  746. }
  747. fprintf(pp, " %s", input_name.c_str());
  748. }
  749. fprintf(pp, " %s", n.name.c_str());
  750. for (int j=1; j<output_size; j++)
  751. {
  752. fprintf(pp, " %s_subncnn_%d", n.name.c_str(), j);
  753. }
  754. if (n.op == "null")
  755. {
  756. // dummy input shape
  757. // fprintf(pp, " 0 0 0");
  758. }
  759. else if (n.op == "Activation")
  760. {
  761. std::string type = n.attr("act_type");
  762. if (type == "relu")
  763. {
  764. // fprintf(pp, " 0=%f", 0.f);
  765. }
  766. }
  767. else if (n.op == "BatchNorm")
  768. {
  769. float eps = 1e-3;
  770. if (n.has_attr("eps")) {
  771. eps = n.attr("eps");
  772. }
  773. std::vector<float> slope_data = n.weight(0);
  774. std::vector<float> bias_data = n.weight(1);
  775. int channels = slope_data.size();
  776. std::vector<float> mean_data = n.weight(2, channels);
  777. std::vector<float> var_data = n.weight(3, channels);
  778. for (int j=0; j<(int)var_data.size(); j++)
  779. {
  780. var_data[j] += eps;
  781. }
  782. fprintf(pp, " 0=%d", channels);
  783. fwrite(slope_data.data(), sizeof(float), slope_data.size(), bp);
  784. fwrite(mean_data.data(), sizeof(float), mean_data.size(), bp);
  785. fwrite(var_data.data(), sizeof(float), var_data.size(), bp);
  786. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  787. }
  788. else if (n.op == "Concat")
  789. {
  790. int dim = n.attr("dim");
  791. fprintf(pp, " 0=%d", dim-1);
  792. }
  793. else if (n.op == "Convolution")
  794. {
  795. int num_filter = n.attr("num_filter");
  796. std::vector<int> kernel = n.attr("kernel");
  797. std::vector<int> dilate = n.attr("dilate");
  798. std::vector<int> stride = n.attr("stride");
  799. std::vector<int> pad = n.attr("pad");
  800. int no_bias = n.attr("no_bias");
  801. int num_group = n.attr("num_group");
  802. std::vector<float> weight_data = n.weight(0);
  803. std::vector<float> bias_data = n.weight(1);
  804. fprintf(pp, " 0=%d", num_filter);
  805. if (kernel.size() == 1) {
  806. fprintf(pp, " 1=%d", kernel[0]);
  807. } else if (kernel.size() == 2) {
  808. fprintf(pp, " 1=%d", kernel[1]);
  809. fprintf(pp, " 11=%d", kernel[0]);
  810. }
  811. if (dilate.size() == 1) {
  812. fprintf(pp, " 2=%d", dilate[0]);
  813. } else if (dilate.size() == 2) {
  814. fprintf(pp, " 2=%d", dilate[1]);
  815. fprintf(pp, " 12=%d", dilate[0]);
  816. }
  817. if (stride.size() == 1) {
  818. fprintf(pp, " 3=%d", stride[0]);
  819. } else if (stride.size() == 2) {
  820. fprintf(pp, " 3=%d", stride[1]);
  821. fprintf(pp, " 13=%d", stride[0]);
  822. }
  823. if (pad.size() == 1) {
  824. fprintf(pp, " 4=%d", pad[0]);
  825. } else if (pad.size() == 2) {
  826. fprintf(pp, " 4=%d", pad[1]);
  827. fprintf(pp, " 14=%d", pad[0]);
  828. }
  829. fprintf(pp, " 5=%d", no_bias == 1 ? 0 : 1);
  830. fprintf(pp, " 6=%d", (int)weight_data.size());
  831. if (num_group > 1) {
  832. fprintf(pp, " 7=%d", num_group);
  833. }
  834. int quantize_tag = 0;
  835. fwrite(&quantize_tag, sizeof(int), 1, bp);
  836. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  837. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  838. }
  839. else if (n.op == "Dropout")
  840. {
  841. // float p = n.attr("p");
  842. // fprintf(pp, " 0=%d", p);
  843. }
  844. else if (n.op == "elemwise_add")
  845. {
  846. int op_type = 0;
  847. fprintf(pp, " 0=%d", op_type);
  848. }
  849. else if (n.op == "elemwise_mul")
  850. {
  851. int op_type = 2;
  852. fprintf(pp, " 0=%d", op_type);
  853. }
  854. else if (n.op == "Embedding")
  855. {
  856. int input_dim = n.attr("input_dim");
  857. int output_dim = n.attr("output_dim");
  858. std::vector<float> weight_data = n.weight(0);
  859. fprintf(pp, " 0=%d", output_dim);
  860. fprintf(pp, " 1=%d", input_dim);
  861. fprintf(pp, " 3=%d", (int)weight_data.size());
  862. int quantize_tag = 0;
  863. fwrite(&quantize_tag, sizeof(int), 1, bp);
  864. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  865. }
  866. else if (n.op == "Flatten")
  867. {
  868. }
  869. else if (n.op == "FullyConnected")
  870. {
  871. int num_hidden = n.attr("num_hidden");
  872. int no_bias = n.attr("no_bias");
  873. // int flatten = n.attr("flatten");
  874. // TODO flatten
  875. std::vector<float> weight_data = n.weight(0);
  876. std::vector<float> bias_data = n.weight(1);
  877. fprintf(pp, " 0=%d", num_hidden);
  878. fprintf(pp, " 1=%d", no_bias == 1 ? 0 : 1);
  879. fprintf(pp, " 2=%d", (int)weight_data.size());
  880. int quantize_tag = 0;
  881. fwrite(&quantize_tag, sizeof(int), 1, bp);
  882. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  883. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  884. }
  885. else if (n.op == "LeakyReLU")
  886. {
  887. std::string type = n.attr("act_type");
  888. if (type == "elu")
  889. {
  890. }
  891. else if (type == "leaky")
  892. {
  893. }
  894. else if (type == "prelu")
  895. {
  896. std::vector<float> weight_data = n.weight(0);
  897. fprintf(pp, " 0=%d", (int)weight_data.size());
  898. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  899. }
  900. }
  901. else if (n.op == "Pooling")
  902. {
  903. std::string pool_type = n.attr("pool_type");
  904. std::vector<int> kernel = n.attr("kernel");
  905. std::vector<int> stride = n.attr("stride");
  906. std::vector<int> pad = n.attr("pad");
  907. std::string pooling_convention = n.attr("pooling_convention");
  908. int global_pool = n.attr("global_pool");
  909. int pool = 0;
  910. if (pool_type == "max")
  911. {
  912. pool = 0;
  913. }
  914. else if (pool_type == "avg")
  915. {
  916. pool = 1;
  917. }
  918. int pad_mode = 1;
  919. if (pooling_convention == "valid")
  920. {
  921. pad_mode = 1;
  922. }
  923. else if (pooling_convention == "full")
  924. {
  925. pad_mode = 0;
  926. }
  927. fprintf(pp, " 0=%d", pool);
  928. if (!kernel.empty())
  929. fprintf(pp, " 1=%d", kernel[0]);
  930. if (!stride.empty())
  931. fprintf(pp, " 2=%d", stride[0]);
  932. if (!pad.empty())
  933. fprintf(pp, " 3=%d", pad[0]);
  934. fprintf(pp, " 4=%d", global_pool);
  935. fprintf(pp, " 5=%d", pad_mode);
  936. }
  937. else if (n.op == "SliceChannel")
  938. {
  939. int num_outputs = n.attr("num_outputs");
  940. int squeeze_axis = n.attr("squeeze_axis");// TODO
  941. fprintf(pp, " -23300=%d", num_outputs);
  942. for (int j=0; j<num_outputs; j++)
  943. {
  944. fprintf(pp, ",-233");
  945. }
  946. }
  947. else if (n.op == "SoftmaxOutput")
  948. {
  949. }
  950. else
  951. {
  952. // TODO op specific params
  953. std::map<std::string, std::string>::const_iterator it = n.attrs.begin();
  954. for (; it != n.attrs.end(); it++)
  955. {
  956. fprintf(stderr, "# %s=%s\n", it->first.c_str(), it->second.c_str());
  957. // fprintf(pp, " %s=%s", it->first.c_str(), it->second.c_str());
  958. }
  959. }
  960. fprintf(pp, "\n");
  961. for (int j=0; j<output_size; j++)
  962. {
  963. int input_uid = i | (j << 16);
  964. if (node_reference.find(input_uid) != node_reference.end())
  965. {
  966. int refcount = node_reference[input_uid];
  967. if (refcount > 1)
  968. {
  969. std::string output_name = n.name;
  970. char splitname[256];
  971. sprintf(splitname, "splitncnn_%d", internal_split);
  972. fprintf(pp, "%-16s %-32s %d %d", "Split", splitname, 1, refcount);
  973. if (j == 0)
  974. {
  975. fprintf(pp, " %s", output_name.c_str());
  976. }
  977. else
  978. {
  979. fprintf(pp, " %s_subncnn_%d", output_name.c_str(), j);
  980. }
  981. for (int k=0; k<refcount; k++)
  982. {
  983. if (j == 0)
  984. {
  985. fprintf(pp, " %s_splitncnn_%d", output_name.c_str(), k);
  986. }
  987. else
  988. {
  989. fprintf(pp, " %s_subncnn_%d_splitncnn_%d", output_name.c_str(), j, k);
  990. }
  991. }
  992. fprintf(pp, "\n");
  993. internal_split++;
  994. }
  995. }
  996. }
  997. }
  998. fclose(pp);
  999. fclose(bp);
  1000. return 0;
  1001. }