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 40 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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457
  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 == "abs")
  608. {
  609. fprintf(pp, "%-16s", "UnaryOp");
  610. }
  611. else if (n.op == "Activation")
  612. {
  613. std::string type = n.attr("act_type");
  614. if (type == "relu")
  615. {
  616. fprintf(pp, "%-16s", "ReLU");
  617. }
  618. else if (type == "sigmoid")
  619. {
  620. fprintf(pp, "%-16s", "Sigmoid");
  621. }
  622. else if (type == "tanh")
  623. {
  624. fprintf(pp, "%-16s", "TanH");
  625. }
  626. }
  627. else if (n.op == "arccos")
  628. {
  629. fprintf(pp, "%-16s", "UnaryOp");
  630. }
  631. else if (n.op == "arcsin")
  632. {
  633. fprintf(pp, "%-16s", "UnaryOp");
  634. }
  635. else if (n.op == "arctan")
  636. {
  637. fprintf(pp, "%-16s", "UnaryOp");
  638. }
  639. else if (n.op == "BatchNorm")
  640. {
  641. fprintf(pp, "%-16s", "BatchNorm");
  642. }
  643. else if (n.op == "broadcast_add")
  644. {
  645. fprintf(pp, "%-16s", "BinaryOp");
  646. }
  647. else if (n.op == "broadcast_div")
  648. {
  649. fprintf(pp, "%-16s", "BinaryOp");
  650. }
  651. else if (n.op == "broadcast_mul")
  652. {
  653. fprintf(pp, "%-16s", "BinaryOp");
  654. }
  655. else if (n.op == "broadcast_sub")
  656. {
  657. fprintf(pp, "%-16s", "BinaryOp");
  658. }
  659. else if (n.op == "ceil")
  660. {
  661. fprintf(pp, "%-16s", "UnaryOp");
  662. }
  663. else if (n.op == "Concat")
  664. {
  665. fprintf(pp, "%-16s", "Concat");
  666. }
  667. else if (n.op == "Convolution")
  668. {
  669. int num_group = n.attr("num_group");
  670. if (num_group > 1) {
  671. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  672. } else {
  673. fprintf(pp, "%-16s", "Convolution");
  674. }
  675. }
  676. else if (n.op == "cos")
  677. {
  678. fprintf(pp, "%-16s", "UnaryOp");
  679. }
  680. else if (n.op == "Dropout")
  681. {
  682. fprintf(pp, "%-16s", "Dropout");
  683. }
  684. else if (n.op == "elemwise_add")
  685. {
  686. fprintf(pp, "%-16s", "BinaryOp");
  687. }
  688. else if (n.op == "elemwise_div")
  689. {
  690. fprintf(pp, "%-16s", "BinaryOp");
  691. }
  692. else if (n.op == "elemwise_mul")
  693. {
  694. fprintf(pp, "%-16s", "BinaryOp");
  695. }
  696. else if (n.op == "elemwise_sub")
  697. {
  698. fprintf(pp, "%-16s", "BinaryOp");
  699. }
  700. else if (n.op == "Embedding")
  701. {
  702. fprintf(pp, "%-16s", "Embed");
  703. }
  704. else if (n.op == "exp")
  705. {
  706. fprintf(pp, "%-16s", "UnaryOp");
  707. }
  708. else if (n.op == "Flatten")
  709. {
  710. fprintf(pp, "%-16s", "Flatten");
  711. }
  712. else if (n.op == "floor")
  713. {
  714. fprintf(pp, "%-16s", "UnaryOp");
  715. }
  716. else if (n.op == "FullyConnected")
  717. {
  718. fprintf(pp, "%-16s", "InnerProduct");
  719. }
  720. else if (n.op == "LeakyReLU")
  721. {
  722. std::string type = n.attr("act_type");
  723. if (type == "elu")
  724. {
  725. fprintf(pp, "%-16s", "ELU");
  726. }
  727. else if (type == "leaky")
  728. {
  729. fprintf(pp, "%-16s", "ReLU");
  730. }
  731. else if (type == "prelu")
  732. {
  733. fprintf(pp, "%-16s", "PReLU");
  734. }
  735. }
  736. else if (n.op == "log")
  737. {
  738. fprintf(pp, "%-16s", "UnaryOp");
  739. }
  740. else if (n.op == "max")
  741. {
  742. fprintf(pp, "%-16s", "Reduction");
  743. }
  744. else if (n.op == "maximum")
  745. {
  746. fprintf(pp, "%-16s", "BinaryOp");
  747. }
  748. else if (n.op == "mean")
  749. {
  750. fprintf(pp, "%-16s", "Reduction");
  751. }
  752. else if (n.op == "min")
  753. {
  754. fprintf(pp, "%-16s", "Reduction");
  755. }
  756. else if (n.op == "minimum")
  757. {
  758. fprintf(pp, "%-16s", "BinaryOp");
  759. }
  760. else if (n.op == "negative")
  761. {
  762. fprintf(pp, "%-16s", "UnaryOp");
  763. }
  764. else if (n.op == "Pooling")
  765. {
  766. fprintf(pp, "%-16s", "Pooling");
  767. }
  768. else if (n.op == "prod")
  769. {
  770. fprintf(pp, "%-16s", "Reduction");
  771. }
  772. else if (n.op == "reciprocal")
  773. {
  774. fprintf(pp, "%-16s", "UnaryOp");
  775. }
  776. else if (n.op == "relu")
  777. {
  778. fprintf(pp, "%-16s", "ReLU");
  779. }
  780. else if (n.op == "sin")
  781. {
  782. fprintf(pp, "%-16s", "UnaryOp");
  783. }
  784. else if (n.op == "SliceChannel")
  785. {
  786. fprintf(pp, "%-16s", "Slice");
  787. output_size = n.attr("num_outputs");
  788. }
  789. else if (n.op == "SoftmaxOutput")
  790. {
  791. fprintf(pp, "%-16s", "Softmax");
  792. }
  793. else if (n.op == "SoftmaxActivation")
  794. {
  795. fprintf(pp, "%-16s", "Softmax");
  796. }
  797. else if (n.op == "sqrt")
  798. {
  799. fprintf(pp, "%-16s", "UnaryOp");
  800. }
  801. else if (n.op == "square")
  802. {
  803. fprintf(pp, "%-16s", "UnaryOp");
  804. }
  805. else if (n.op == "sum")
  806. {
  807. fprintf(pp, "%-16s", "Reduction");
  808. }
  809. else if (n.op == "tan")
  810. {
  811. fprintf(pp, "%-16s", "UnaryOp");
  812. }
  813. else if (n.op == "tanh")
  814. {
  815. fprintf(pp, "%-16s", "TanH");
  816. }
  817. else
  818. {
  819. fprintf(stderr, "%s not supported yet!\n", n.op.c_str());
  820. fprintf(pp, "%-16s", n.op.c_str());
  821. }
  822. int input_size = n.inputs.size();
  823. for (int j=0; j<(int)n.inputs.size(); j++)
  824. {
  825. int input_index = n.inputs[j];
  826. if (nodes[input_index].is_weight())
  827. {
  828. input_size--;
  829. }
  830. }
  831. if (n.op == "SoftmaxOutput")
  832. {
  833. // drop label
  834. input_size--;
  835. }
  836. fprintf(pp, " %-32s %d %d", n.name.c_str(), input_size, output_size);
  837. for (int j=0; j<(int)n.inputs.size(); j++)
  838. {
  839. int input_index = n.inputs[j];
  840. int subinput_index = n.subinputs[j];
  841. if (nodes[input_index].is_weight())
  842. {
  843. continue;
  844. }
  845. if (n.op == "SoftmaxOutput")
  846. {
  847. // drop label
  848. if (j == 1)
  849. continue;
  850. }
  851. std::string input_name = nodes[input_index].name;
  852. if (subinput_index != 0)
  853. {
  854. char subinputsuffix[256];
  855. sprintf(subinputsuffix, "_subncnn_%d", subinput_index);
  856. input_name = input_name + subinputsuffix;
  857. }
  858. int input_uid = input_index | (subinput_index << 16);
  859. if (node_reference.find(input_uid) != node_reference.end())
  860. {
  861. int refidx = node_reference[input_uid] - 1;
  862. node_reference[input_uid] = refidx;
  863. char splitsuffix[256];
  864. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  865. input_name = input_name + splitsuffix;
  866. }
  867. fprintf(pp, " %s", input_name.c_str());
  868. }
  869. fprintf(pp, " %s", n.name.c_str());
  870. for (int j=1; j<output_size; j++)
  871. {
  872. fprintf(pp, " %s_subncnn_%d", n.name.c_str(), j);
  873. }
  874. if (n.op == "null")
  875. {
  876. // dummy input shape
  877. // fprintf(pp, " 0 0 0");
  878. }
  879. else if (n.op == "abs")
  880. {
  881. int op_type = 0;
  882. fprintf(pp, " 0=%d", op_type);
  883. }
  884. else if (n.op == "Activation")
  885. {
  886. std::string type = n.attr("act_type");
  887. if (type == "relu")
  888. {
  889. // fprintf(pp, " 0=%f", 0.f);
  890. }
  891. }
  892. else if (n.op == "arccos")
  893. {
  894. int op_type = 13;
  895. fprintf(pp, " 0=%d", op_type);
  896. }
  897. else if (n.op == "arcsin")
  898. {
  899. int op_type = 12;
  900. fprintf(pp, " 0=%d", op_type);
  901. }
  902. else if (n.op == "arctan")
  903. {
  904. int op_type = 14;
  905. fprintf(pp, " 0=%d", op_type);
  906. }
  907. else if (n.op == "BatchNorm")
  908. {
  909. float eps = 1e-3;
  910. if (n.has_attr("eps")) {
  911. eps = n.attr("eps");
  912. }
  913. std::vector<float> slope_data = n.weight(0);
  914. std::vector<float> bias_data = n.weight(1);
  915. int channels = slope_data.size();
  916. std::vector<float> mean_data = n.weight(2, channels);
  917. std::vector<float> var_data = n.weight(3, channels);
  918. for (int j=0; j<(int)var_data.size(); j++)
  919. {
  920. var_data[j] += eps;
  921. }
  922. fprintf(pp, " 0=%d", channels);
  923. fwrite(slope_data.data(), sizeof(float), slope_data.size(), bp);
  924. fwrite(mean_data.data(), sizeof(float), mean_data.size(), bp);
  925. fwrite(var_data.data(), sizeof(float), var_data.size(), bp);
  926. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  927. }
  928. else if (n.op == "broadcast_add")
  929. {
  930. int op_type = 0;
  931. fprintf(pp, " 0=%d", op_type);
  932. }
  933. else if (n.op == "broadcast_div")
  934. {
  935. int op_type = 3;
  936. fprintf(pp, " 0=%d", op_type);
  937. }
  938. else if (n.op == "broadcast_mul")
  939. {
  940. int op_type = 2;
  941. fprintf(pp, " 0=%d", op_type);
  942. }
  943. else if (n.op == "broadcast_sub")
  944. {
  945. int op_type = 1;
  946. fprintf(pp, " 0=%d", op_type);
  947. }
  948. else if (n.op == "ceil")
  949. {
  950. int op_type = 3;
  951. fprintf(pp, " 0=%d", op_type);
  952. }
  953. else if (n.op == "Concat")
  954. {
  955. int dim = n.has_attr("dim") ? n.attr("dim") : 1;
  956. fprintf(pp, " 0=%d", dim-1);
  957. }
  958. else if (n.op == "Convolution")
  959. {
  960. int num_filter = n.attr("num_filter");
  961. std::vector<int> kernel = n.attr("kernel");
  962. std::vector<int> dilate = n.attr("dilate");
  963. std::vector<int> stride = n.attr("stride");
  964. std::vector<int> pad = n.attr("pad");
  965. int no_bias = n.attr("no_bias");
  966. int num_group = n.attr("num_group");
  967. std::vector<float> weight_data = n.weight(0);
  968. std::vector<float> bias_data = n.weight(1);
  969. fprintf(pp, " 0=%d", num_filter);
  970. if (kernel.size() == 1) {
  971. fprintf(pp, " 1=%d", kernel[0]);
  972. } else if (kernel.size() == 2) {
  973. fprintf(pp, " 1=%d", kernel[1]);
  974. fprintf(pp, " 11=%d", kernel[0]);
  975. }
  976. if (dilate.size() == 1) {
  977. fprintf(pp, " 2=%d", dilate[0]);
  978. } else if (dilate.size() == 2) {
  979. fprintf(pp, " 2=%d", dilate[1]);
  980. fprintf(pp, " 12=%d", dilate[0]);
  981. }
  982. if (stride.size() == 1) {
  983. fprintf(pp, " 3=%d", stride[0]);
  984. } else if (stride.size() == 2) {
  985. fprintf(pp, " 3=%d", stride[1]);
  986. fprintf(pp, " 13=%d", stride[0]);
  987. }
  988. if (pad.size() == 1) {
  989. fprintf(pp, " 4=%d", pad[0]);
  990. } else if (pad.size() == 2) {
  991. fprintf(pp, " 4=%d", pad[1]);
  992. fprintf(pp, " 14=%d", pad[0]);
  993. }
  994. fprintf(pp, " 5=%d", no_bias == 1 ? 0 : 1);
  995. fprintf(pp, " 6=%d", (int)weight_data.size());
  996. if (num_group > 1) {
  997. fprintf(pp, " 7=%d", num_group);
  998. }
  999. int quantize_tag = 0;
  1000. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1001. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1002. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1003. }
  1004. else if (n.op == "cos")
  1005. {
  1006. int op_type = 10;
  1007. fprintf(pp, " 0=%d", op_type);
  1008. }
  1009. else if (n.op == "Dropout")
  1010. {
  1011. // float p = n.attr("p");
  1012. // fprintf(pp, " 0=%d", p);
  1013. }
  1014. else if (n.op == "elemwise_add")
  1015. {
  1016. int op_type = 0;
  1017. fprintf(pp, " 0=%d", op_type);
  1018. }
  1019. else if (n.op == "elemwise_div")
  1020. {
  1021. int op_type = 3;
  1022. fprintf(pp, " 0=%d", op_type);
  1023. }
  1024. else if (n.op == "elemwise_mul")
  1025. {
  1026. int op_type = 2;
  1027. fprintf(pp, " 0=%d", op_type);
  1028. }
  1029. else if (n.op == "elemwise_sub")
  1030. {
  1031. int op_type = 1;
  1032. fprintf(pp, " 0=%d", op_type);
  1033. }
  1034. else if (n.op == "Embedding")
  1035. {
  1036. int input_dim = n.attr("input_dim");
  1037. int output_dim = n.attr("output_dim");
  1038. std::vector<float> weight_data = n.weight(0);
  1039. fprintf(pp, " 0=%d", output_dim);
  1040. fprintf(pp, " 1=%d", input_dim);
  1041. fprintf(pp, " 3=%d", (int)weight_data.size());
  1042. int quantize_tag = 0;
  1043. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1044. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1045. }
  1046. else if (n.op == "exp")
  1047. {
  1048. int op_type = 7;
  1049. fprintf(pp, " 0=%d", op_type);
  1050. }
  1051. else if (n.op == "Flatten")
  1052. {
  1053. }
  1054. else if (n.op == "floor")
  1055. {
  1056. int op_type = 2;
  1057. fprintf(pp, " 0=%d", op_type);
  1058. }
  1059. else if (n.op == "FullyConnected")
  1060. {
  1061. int num_hidden = n.attr("num_hidden");
  1062. int no_bias = n.attr("no_bias");
  1063. // int flatten = n.attr("flatten");
  1064. // TODO flatten
  1065. std::vector<float> weight_data = n.weight(0);
  1066. std::vector<float> bias_data = n.weight(1);
  1067. fprintf(pp, " 0=%d", num_hidden);
  1068. fprintf(pp, " 1=%d", no_bias == 1 ? 0 : 1);
  1069. fprintf(pp, " 2=%d", (int)weight_data.size());
  1070. int quantize_tag = 0;
  1071. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1072. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1073. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1074. }
  1075. else if (n.op == "LeakyReLU")
  1076. {
  1077. std::string type = n.attr("act_type");
  1078. if (type == "elu")
  1079. {
  1080. float slope = n.attr("slope");
  1081. fprintf(pp, " 0=%f", slope);
  1082. }
  1083. else if (type == "leaky")
  1084. {
  1085. float slope = n.attr("slope");
  1086. fprintf(pp, " 0=%f", slope);
  1087. }
  1088. else if (type == "prelu")
  1089. {
  1090. std::vector<float> weight_data = n.weight(0);
  1091. fprintf(pp, " 0=%d", (int)weight_data.size());
  1092. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1093. }
  1094. }
  1095. else if (n.op == "log")
  1096. {
  1097. int op_type = 8;
  1098. fprintf(pp, " 0=%d", op_type);
  1099. }
  1100. else if (n.op == "max")
  1101. {
  1102. int operation = 4;
  1103. fprintf(pp, " 0=%d", operation);
  1104. }
  1105. else if (n.op == "maximum")
  1106. {
  1107. int op_type = 4;
  1108. fprintf(pp, " 0=%d", op_type);
  1109. }
  1110. else if (n.op == "mean")
  1111. {
  1112. int operation = 3;
  1113. fprintf(pp, " 0=%d", operation);
  1114. }
  1115. else if (n.op == "min")
  1116. {
  1117. int operation = 5;
  1118. fprintf(pp, " 0=%d", operation);
  1119. }
  1120. else if (n.op == "minimum")
  1121. {
  1122. int op_type = 5;
  1123. fprintf(pp, " 0=%d", op_type);
  1124. }
  1125. else if (n.op == "negative")
  1126. {
  1127. int op_type = 1;
  1128. fprintf(pp, " 0=%d", op_type);
  1129. }
  1130. else if (n.op == "Pooling")
  1131. {
  1132. std::string pool_type = n.attr("pool_type");
  1133. std::vector<int> kernel = n.attr("kernel");
  1134. std::vector<int> stride = n.attr("stride");
  1135. std::vector<int> pad = n.attr("pad");
  1136. std::string pooling_convention = n.attr("pooling_convention");
  1137. int global_pool = n.attr("global_pool");
  1138. int pool = 0;
  1139. if (pool_type == "max")
  1140. {
  1141. pool = 0;
  1142. }
  1143. else if (pool_type == "avg")
  1144. {
  1145. pool = 1;
  1146. }
  1147. int pad_mode = 1;
  1148. if (pooling_convention == "valid")
  1149. {
  1150. pad_mode = 1;
  1151. }
  1152. else if (pooling_convention == "full")
  1153. {
  1154. pad_mode = 0;
  1155. }
  1156. fprintf(pp, " 0=%d", pool);
  1157. if (!kernel.empty())
  1158. fprintf(pp, " 1=%d", kernel[0]);
  1159. if (!stride.empty())
  1160. fprintf(pp, " 2=%d", stride[0]);
  1161. if (!pad.empty())
  1162. fprintf(pp, " 3=%d", pad[0]);
  1163. fprintf(pp, " 4=%d", global_pool);
  1164. fprintf(pp, " 5=%d", pad_mode);
  1165. }
  1166. else if (n.op == "prod")
  1167. {
  1168. int operation = 6;
  1169. fprintf(pp, " 0=%d", operation);
  1170. }
  1171. else if (n.op == "reciprocal")
  1172. {
  1173. int op_type = 15;
  1174. fprintf(pp, " 0=%d", op_type);
  1175. }
  1176. else if (n.op == "relu")
  1177. {
  1178. }
  1179. else if (n.op == "sin")
  1180. {
  1181. int op_type = 9;
  1182. fprintf(pp, " 0=%d", op_type);
  1183. }
  1184. else if (n.op == "SliceChannel")
  1185. {
  1186. int num_outputs = n.attr("num_outputs");
  1187. int squeeze_axis = n.attr("squeeze_axis");// TODO
  1188. fprintf(pp, " -23300=%d", num_outputs);
  1189. for (int j=0; j<num_outputs; j++)
  1190. {
  1191. fprintf(pp, ",-233");
  1192. }
  1193. }
  1194. else if (n.op == "SoftmaxOutput")
  1195. {
  1196. }
  1197. else if (n.op == "sqrt")
  1198. {
  1199. int op_type = 5;
  1200. fprintf(pp, " 0=%d", op_type);
  1201. }
  1202. else if (n.op == "square")
  1203. {
  1204. int op_type = 4;
  1205. fprintf(pp, " 0=%d", op_type);
  1206. }
  1207. else if (n.op == "sum")
  1208. {
  1209. int operation = 0;
  1210. fprintf(pp, " 0=%d", operation);
  1211. }
  1212. else if (n.op == "tan")
  1213. {
  1214. int op_type = 11;
  1215. fprintf(pp, " 0=%d", op_type);
  1216. }
  1217. else if (n.op == "tanh")
  1218. {
  1219. }
  1220. else
  1221. {
  1222. // TODO op specific params
  1223. std::map<std::string, std::string>::const_iterator it = n.attrs.begin();
  1224. for (; it != n.attrs.end(); it++)
  1225. {
  1226. fprintf(stderr, "# %s=%s\n", it->first.c_str(), it->second.c_str());
  1227. // fprintf(pp, " %s=%s", it->first.c_str(), it->second.c_str());
  1228. }
  1229. }
  1230. fprintf(pp, "\n");
  1231. for (int j=0; j<output_size; j++)
  1232. {
  1233. int input_uid = i | (j << 16);
  1234. if (node_reference.find(input_uid) != node_reference.end())
  1235. {
  1236. int refcount = node_reference[input_uid];
  1237. if (refcount > 1)
  1238. {
  1239. std::string output_name = n.name;
  1240. char splitname[256];
  1241. sprintf(splitname, "splitncnn_%d", internal_split);
  1242. fprintf(pp, "%-16s %-32s %d %d", "Split", splitname, 1, refcount);
  1243. if (j == 0)
  1244. {
  1245. fprintf(pp, " %s", output_name.c_str());
  1246. }
  1247. else
  1248. {
  1249. fprintf(pp, " %s_subncnn_%d", output_name.c_str(), j);
  1250. }
  1251. for (int k=0; k<refcount; k++)
  1252. {
  1253. if (j == 0)
  1254. {
  1255. fprintf(pp, " %s_splitncnn_%d", output_name.c_str(), k);
  1256. }
  1257. else
  1258. {
  1259. fprintf(pp, " %s_subncnn_%d_splitncnn_%d", output_name.c_str(), j, k);
  1260. }
  1261. }
  1262. fprintf(pp, "\n");
  1263. internal_split++;
  1264. }
  1265. }
  1266. }
  1267. }
  1268. fclose(pp);
  1269. fclose(bp);
  1270. return 0;
  1271. }