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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 MXNetNode
  22. {
  23. public:
  24. std::string op;
  25. std::string name;
  26. std::map<std::string, std::string> attrs;
  27. std::vector<int> inputs;
  28. };
  29. class MXNetParam
  30. {
  31. public:
  32. std::string name;
  33. std::vector<float> data;
  34. };
  35. static void replace_backslash_doublequote_dollar(char* s)
  36. {
  37. char* a = s;
  38. char* b = s+1;
  39. while (*a && *b)
  40. {
  41. if (*a == '\\' && *b == '\"')
  42. {
  43. *b = '$';
  44. }
  45. a++;
  46. b++;
  47. }
  48. }
  49. static std::vector<int> parse_input_list(const char* s)
  50. {
  51. std::vector<int> inputs;
  52. if (memcmp(s, "[]", 2) == 0)
  53. return inputs;
  54. int nscan = 0;
  55. int nconsumed = 0;
  56. int id;
  57. int c = 1;// skip leading [
  58. nscan = sscanf(s + c, "[%d, %*d, %*d]%n", &id, &nconsumed);
  59. while (nscan == 1)
  60. {
  61. inputs.push_back(id);
  62. // fprintf(stderr, "%d\n", id);
  63. c += nconsumed;
  64. nscan = sscanf(s + c, "%*[^[][%d, %*d, %*d]%n", &id, &nconsumed);
  65. }
  66. return inputs;
  67. }
  68. static bool read_mxnet_json(const char* jsonpath, std::vector<MXNetNode>& nodes)
  69. {
  70. FILE* fp = fopen(jsonpath, "rb");
  71. if (!fp)
  72. {
  73. fprintf(stderr, "fopen %s failed\n", jsonpath);
  74. return false;
  75. }
  76. int internal_unknown = 0;
  77. char line[1024];
  78. //{
  79. fgets(line, 1024, fp);
  80. MXNetNode n;
  81. bool in_nodes_list = false;
  82. bool in_node_block = false;
  83. bool in_attr_block = false;
  84. while (!feof(fp))
  85. {
  86. char* s = fgets(line, 1024, fp);
  87. if (!s)
  88. break;
  89. if (in_attr_block)
  90. {
  91. // },
  92. if (memcmp(line, " }", 7) == 0)
  93. {
  94. in_attr_block = false;
  95. continue;
  96. }
  97. // replace \" with \$
  98. replace_backslash_doublequote_dollar(line);
  99. // "kernel": "(7,7)",
  100. char key[256] = {0};
  101. char value[256] = {0};
  102. int nscan = sscanf(line, " \"%255[^\"]\": \"%255[^\"]\",", key, value);
  103. if (nscan == 2)
  104. {
  105. n.attrs[key] = value;
  106. // fprintf(stderr, "# %s = %s\n", key, value);
  107. continue;
  108. }
  109. }
  110. if (in_node_block)
  111. {
  112. // },
  113. if (memcmp(line, " }", 5) == 0)
  114. {
  115. // new node
  116. if (n.name.empty())
  117. {
  118. // assign default unknown name
  119. char unknownname[256];
  120. sprintf(unknownname, "unknownncnn_%d", internal_unknown);
  121. n.name = unknownname;
  122. internal_unknown++;
  123. }
  124. nodes.push_back(n);
  125. in_node_block = false;
  126. continue;
  127. }
  128. int nscan;
  129. // "op": "Convolution",
  130. char op[256] = {0};
  131. nscan = sscanf(line, " \"op\": \"%255[^\"]\",", op);
  132. if (nscan == 1)
  133. {
  134. n.op = op;
  135. // fprintf(stderr, "op = %s\n", op);
  136. continue;
  137. }
  138. // "name": "conv0",
  139. char name[256] = {0};
  140. nscan = sscanf(line, " \"name\": \"%255[^\"]\",", name);
  141. if (nscan == 1)
  142. {
  143. n.name = name;
  144. // fprintf(stderr, "name = %s\n", name);
  145. continue;
  146. }
  147. // "inputs": []
  148. char inputs[256] = {0};
  149. nscan = sscanf(line, " \"inputs\": %255[^\n]", inputs);
  150. if (nscan == 1)
  151. {
  152. n.inputs = parse_input_list(inputs);
  153. // fprintf(stderr, "inputs = %s\n", inputs);
  154. continue;
  155. }
  156. // replace \" with \$
  157. replace_backslash_doublequote_dollar(line);
  158. // "attr": {"__init__": "[\"zero\", {}]"},
  159. char key[256] = {0};
  160. char value[256] = {0};
  161. nscan = sscanf(line, " \"attr\": {\"%255[^\"]\": \"%255[^\"]\"},", key, value);
  162. if (nscan == 2)
  163. {
  164. n.attrs[key] = value;
  165. // fprintf(stderr, "# %s = %s\n", key, value);
  166. continue;
  167. }
  168. // "attr": {
  169. if (memcmp(line, " \"attr\": {", 15) == 0)
  170. {
  171. in_attr_block = true;
  172. continue;
  173. }
  174. }
  175. if (in_nodes_list)
  176. {
  177. // ],
  178. if (memcmp(line, " ],", 4) == 0)
  179. {
  180. in_nodes_list = false;
  181. // all nodes parsed
  182. break;
  183. }
  184. // {
  185. if (memcmp(line, " {", 5) == 0)
  186. {
  187. n = MXNetNode();
  188. in_node_block = true;
  189. continue;
  190. }
  191. }
  192. // "nodes": [
  193. if (memcmp(line, " \"nodes\": [", 12) == 0)
  194. {
  195. in_nodes_list = true;
  196. continue;
  197. }
  198. }
  199. fclose(fp);
  200. return true;
  201. }
  202. static bool read_mxnet_param(const char* parampath, std::vector<MXNetParam>& params)
  203. {
  204. FILE* fp = fopen(parampath, "rb");
  205. if (!fp)
  206. {
  207. fprintf(stderr, "fopen %s failed\n", parampath);
  208. return false;
  209. }
  210. uint64_t header;
  211. uint64_t reserved;
  212. fread(&header, 1, sizeof(uint64_t), fp);
  213. fread(&reserved, 1, sizeof(uint64_t), fp);
  214. // NDArray vec
  215. // each data
  216. uint64_t data_count;
  217. fread(&data_count, 1, sizeof(uint64_t), fp);
  218. // fprintf(stderr, "data count = %d\n", (int)data_count);
  219. for (int i = 0; i < (int)data_count; i++)
  220. {
  221. uint32_t magic;// 0xF993FAC9
  222. fread(&magic, 1, sizeof(uint32_t), fp);
  223. int32_t stype;
  224. fread(&stype, 1, sizeof(int32_t), fp);
  225. // shape
  226. uint32_t ndim;
  227. fread(&ndim, 1, sizeof(uint32_t), fp);
  228. std::vector<int64_t> shape;
  229. shape.resize(ndim);
  230. fread(&shape[0], 1, ndim * sizeof(int64_t), fp);
  231. // context
  232. int32_t dev_type;
  233. int32_t dev_id;
  234. fread(&dev_type, 1, sizeof(int32_t), fp);
  235. fread(&dev_id, 1, sizeof(int32_t), fp);
  236. int32_t type_flag;
  237. fread(&type_flag, 1, sizeof(int32_t), fp);
  238. // data
  239. size_t len = 0;
  240. if (shape.size() == 1) len = shape[0];
  241. if (shape.size() == 2) len = shape[0] * shape[1];
  242. if (shape.size() == 3) len = shape[0] * shape[1] * shape[2];
  243. if (shape.size() == 4) len = shape[0] * shape[1] * shape[2] * shape[3];
  244. MXNetParam p;
  245. p.data.resize(len);
  246. fread(&p.data[0], 1, len * sizeof(float), fp);
  247. params.push_back(p);
  248. // fprintf(stderr, "%u read\n", len);
  249. }
  250. // each name
  251. uint64_t name_count;
  252. fread(&name_count, 1, sizeof(uint64_t), fp);
  253. // fprintf(stderr, "name count = %d\n", (int)name_count);
  254. for (int i = 0; i < (int)name_count; i++)
  255. {
  256. uint64_t len;
  257. fread(&len, 1, sizeof(uint64_t), fp);
  258. MXNetParam& p = params[i];
  259. p.name.resize(len);
  260. fread((char*)p.name.data(), 1, len, fp);
  261. // fprintf(stderr, "%s read\n", name.c_str());
  262. }
  263. fclose(fp);
  264. return true;
  265. }
  266. static bool find_param(const std::vector<MXNetParam>& params, const std::string& name, MXNetParam& p)
  267. {
  268. for (int i=0; i<params.size(); i++)
  269. {
  270. if (params[i].name == name)
  271. {
  272. p = params[i];
  273. return true;
  274. }
  275. }
  276. return false;
  277. }
  278. static bool vector_has(const std::vector<int>& v, int id)
  279. {
  280. for (int i=0; i<v.size(); i++)
  281. {
  282. if (v[i] == id)
  283. return true;
  284. }
  285. return false;
  286. }
  287. int main(int argc, char** argv)
  288. {
  289. const char* jsonpath = argv[1];
  290. const char* parampath = argv[2];
  291. const char* ncnn_prototxt = argc >= 5 ? argv[3] : "ncnn.proto";
  292. const char* ncnn_modelbin = argc >= 5 ? argv[4] : "ncnn.bin";
  293. std::vector<MXNetNode> nodes;
  294. std::vector<MXNetParam> params;
  295. read_mxnet_json(jsonpath, nodes);
  296. read_mxnet_param(parampath, params);
  297. FILE* pp = fopen(ncnn_prototxt, "wb");
  298. FILE* bp = fopen(ncnn_modelbin, "wb");
  299. // magic
  300. fprintf(pp, "7767517\n");
  301. int node_count = nodes.size();
  302. // node reference
  303. std::map<int, int> node_reference;
  304. // input node
  305. std::vector<int> input_nodes;
  306. // weight node
  307. std::vector<int> weight_nodes;
  308. // weight init node
  309. std::vector<int> weight_init_nodes;
  310. // global definition line
  311. // [layer count] [blob count]
  312. std::set<std::string> blob_names;
  313. for (int i=0; i<node_count; i++)
  314. {
  315. const MXNetNode& n = nodes[i];
  316. const std::string& output_name = n.name;
  317. if (n.op == "null")
  318. {
  319. MXNetParam p;
  320. if (find_param(params, output_name, p))
  321. {
  322. weight_nodes.push_back(i);
  323. }
  324. else
  325. {
  326. if (n.attrs.find("__init__") != n.attrs.end())
  327. {
  328. weight_init_nodes.push_back(i);
  329. }
  330. else
  331. {
  332. // null node without data, treat it as network input
  333. input_nodes.push_back(i);
  334. }
  335. }
  336. continue;
  337. }
  338. // input
  339. for (int j=0; j<n.inputs.size(); j++)
  340. {
  341. int input_index = n.inputs[j];
  342. if (vector_has(weight_nodes, input_index))
  343. {
  344. continue;
  345. }
  346. if (vector_has(weight_init_nodes, input_index))
  347. {
  348. continue;
  349. }
  350. const std::string& input_name = nodes[input_index].name;
  351. // fprintf(stderr, "input = %s\n", input_name.c_str());
  352. blob_names.insert(input_name);
  353. if (node_reference.find(input_index) == node_reference.end())
  354. {
  355. node_reference[input_index] = 1;
  356. }
  357. else
  358. {
  359. node_reference[input_index] = node_reference[input_index] + 1;
  360. }
  361. }
  362. // output
  363. // fprintf(stderr, "output = %s\n", output_name.c_str());
  364. blob_names.insert(output_name);
  365. }
  366. // remove node_reference entry with reference equals to one
  367. int splitncnn_blob_count = 0;
  368. std::map<int, int>::iterator it = node_reference.begin();
  369. while (it != node_reference.end())
  370. {
  371. if (it->second == 1)
  372. {
  373. node_reference.erase(it++);
  374. }
  375. else
  376. {
  377. splitncnn_blob_count += it->second;
  378. // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second);
  379. ++it;
  380. }
  381. }
  382. fprintf(pp, "%lu %lu\n", node_count + node_reference.size() + input_nodes.size() - weight_nodes.size() - weight_init_nodes.size(), blob_names.size() + input_nodes.size() + splitncnn_blob_count);
  383. int internal_split = 0;
  384. for (int i=0; i<node_count; i++)
  385. {
  386. const MXNetNode& n = nodes[i];
  387. if (n.op == "null")
  388. {
  389. if (vector_has(weight_nodes, i))
  390. {
  391. continue;
  392. }
  393. if (vector_has(weight_init_nodes, i))
  394. {
  395. continue;
  396. }
  397. if (vector_has(input_nodes, i))
  398. {
  399. fprintf(pp, "%-16s", "Input");
  400. }
  401. }
  402. else
  403. {
  404. fprintf(pp, "%-16s", n.op.c_str());
  405. }
  406. int input_size = n.inputs.size();
  407. for (int j=0; j<n.inputs.size(); j++)
  408. {
  409. int input_index = n.inputs[j];
  410. if (vector_has(weight_nodes, input_index))
  411. {
  412. input_size--;
  413. }
  414. if (vector_has(weight_init_nodes, input_index))
  415. {
  416. input_size--;
  417. }
  418. }
  419. fprintf(pp, " %-32s %d 1", n.name.c_str(), input_size);
  420. for (int j=0; j<n.inputs.size(); j++)
  421. {
  422. int input_index = n.inputs[j];
  423. if (vector_has(weight_nodes, input_index))
  424. {
  425. continue;
  426. }
  427. if (vector_has(weight_init_nodes, input_index))
  428. {
  429. continue;
  430. }
  431. std::string input_name = nodes[input_index].name;
  432. if (node_reference.find(input_index) != node_reference.end())
  433. {
  434. int refidx = node_reference[input_index] - 1;
  435. node_reference[input_index] = refidx;
  436. char splitsuffix[256];
  437. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  438. input_name = input_name + splitsuffix;
  439. }
  440. fprintf(pp, " %s", input_name.c_str());
  441. }
  442. fprintf(pp, " %s", n.name.c_str());
  443. // TODO op specific params
  444. fprintf(pp, "\n");
  445. if (node_reference.find(i) != node_reference.end())
  446. {
  447. int refcount = node_reference[i];
  448. if (refcount > 1)
  449. {
  450. std::string output_name = n.name;
  451. char splitname[256];
  452. sprintf(splitname, "splitncnn_%d", internal_split);
  453. fprintf(pp, "%-16s %-32s %d %d", "Split", splitname, 1, refcount);
  454. fprintf(pp, " %s", output_name.c_str());
  455. for (int j=0; j<refcount; j++)
  456. {
  457. fprintf(pp, " %s_splitncnn_%d", output_name.c_str(), j);
  458. }
  459. fprintf(pp, "\n");
  460. internal_split++;
  461. }
  462. }
  463. }
  464. fclose(pp);
  465. fclose(bp);
  466. return 0;
  467. }