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 67 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
8 years ago
8 years ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283
  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. operator std::vector<float>() const { return _n->attr_af(_key); }
  37. };
  38. AttrProxy attr(const char* key) const { return AttrProxy(this, key); }
  39. int attr_i(const char* key) const;
  40. float attr_f(const char* key) const;
  41. std::string attr_s(const char* key) const;
  42. std::vector<int> attr_ai(const char* key) const;
  43. std::vector<float> attr_af(const char* key) const;
  44. public:
  45. bool is_weight() const;
  46. bool has_weight(int i) const;
  47. std::vector<float> weight(int i, int init_len = 0) const;
  48. std::vector<MXNetNode>* nodes;// reference
  49. std::vector<MXNetParam>* params;// reference
  50. public:
  51. std::string op;
  52. std::string name;
  53. int output_size;
  54. std::map<std::string, std::string> attrs;
  55. std::vector<int> inputs;
  56. std::vector<int> subinputs;
  57. std::vector<int> weights;
  58. };
  59. class MXNetParam
  60. {
  61. public:
  62. std::string name;
  63. std::vector<float> data;
  64. std::string init;
  65. };
  66. bool MXNetNode::has_attr(const char* key) const
  67. {
  68. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  69. return it != attrs.end();
  70. }
  71. int MXNetNode::attr_i(const char* key) const
  72. {
  73. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  74. if (it == attrs.end())
  75. return 0;
  76. if (it->second == "False")
  77. return 0;
  78. if (it->second == "True")
  79. return 1;
  80. int i = 0;
  81. int nscan = sscanf(it->second.c_str(), "%d", &i);
  82. if (nscan != 1)
  83. return 0;
  84. return i;
  85. }
  86. float MXNetNode::attr_f(const char* key) const
  87. {
  88. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  89. if (it == attrs.end())
  90. return 0.f;
  91. float f = 0;
  92. int nscan = sscanf(it->second.c_str(), "%f", &f);
  93. if (nscan != 1)
  94. return 0.f;
  95. return f;
  96. }
  97. std::string MXNetNode::attr_s(const char* key) const
  98. {
  99. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  100. if (it == attrs.end())
  101. return std::string();
  102. return it->second;
  103. }
  104. std::vector<int> MXNetNode::attr_ai(const char* key) const
  105. {
  106. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  107. if (it == attrs.end())
  108. return std::vector<int>();
  109. // (1,2,3)
  110. std::vector<int> list;
  111. int i = 0;
  112. int c = 0;
  113. int nconsumed = 0;
  114. int nscan = sscanf(it->second.c_str() + c, "%*[(,]%d%n", &i, &nconsumed);
  115. while (nscan == 1)
  116. {
  117. list.push_back(i);
  118. // fprintf(stderr, "%d\n", i);
  119. i = 0;
  120. c += nconsumed;
  121. nscan = sscanf(it->second.c_str() + c, "%*[(,]%d%n", &i, &nconsumed);
  122. }
  123. return list;
  124. }
  125. std::vector<float> MXNetNode::attr_af(const char* key) const
  126. {
  127. const std::map<std::string, std::string>::const_iterator it = attrs.find(key);
  128. if (it == attrs.end())
  129. return std::vector<float>();
  130. // (0.1,0.2,0.3)
  131. std::vector<float> list;
  132. float i = 0.f;
  133. int c = 0;
  134. int nconsumed = 0;
  135. int nscan = sscanf(it->second.c_str() + c, "%*[(,]%f%n", &i, &nconsumed);
  136. while (nscan == 1)
  137. {
  138. list.push_back(i);
  139. // fprintf(stderr, "%f\n", i);
  140. i = 0.f;
  141. c += nconsumed;
  142. nscan = sscanf(it->second.c_str() + c, "%*[(,]%f%n", &i, &nconsumed);
  143. }
  144. return list;
  145. }
  146. bool MXNetNode::is_weight() const
  147. {
  148. for (int i=0; i<(int)(*params).size(); i++)
  149. {
  150. const MXNetParam& p = (*params)[i];
  151. if (p.name == name)
  152. return true;
  153. }
  154. return false;
  155. }
  156. bool MXNetNode::has_weight(int i) const
  157. {
  158. if (i < 0 || i >= (int)weights.size())
  159. return false;
  160. const std::string& name = (*nodes)[ weights[i] ].name;
  161. for (int i=0; i<(int)(*params).size(); i++)
  162. {
  163. const MXNetParam& p = (*params)[i];
  164. if (p.name == name)
  165. return true;
  166. }
  167. return false;
  168. }
  169. std::vector<float> MXNetNode::weight(int i, int init_len) const
  170. {
  171. if (i < 0 || i >= (int)weights.size())
  172. return std::vector<float>();
  173. const std::string& name = (*nodes)[ weights[i] ].name;
  174. for (int i=0; i<(int)(*params).size(); i++)
  175. {
  176. const MXNetParam& p = (*params)[i];
  177. if (p.name != name)
  178. continue;
  179. if (!p.data.empty())
  180. return p.data;
  181. std::vector<float> data;
  182. if (!p.init.empty() && init_len != 0)
  183. {
  184. if (p.init == "[\\$zero\\$, {}]" || p.init == "[\\\"zero\\\", {}]" || p.init == "zeros")
  185. {
  186. data.resize(init_len, 0.f);
  187. }
  188. else if (p.init == "[\\$one\\$, {}]" || p.init == "[\\\"one\\\", {}]" || p.init == "ones")
  189. {
  190. data.resize(init_len, 1.f);
  191. }
  192. }
  193. return data;
  194. }
  195. return std::vector<float>();
  196. }
  197. static void replace_backslash_doublequote_dollar(char* s)
  198. {
  199. char* a = s;
  200. char* b = s+1;
  201. while (*a && *b)
  202. {
  203. if (*a == '\\' && *b == '\"')
  204. {
  205. *b = '$';
  206. }
  207. a++;
  208. b++;
  209. }
  210. }
  211. static void parse_input_list(const char* s, std::vector<int>& inputs, std::vector<int>& subinputs)
  212. {
  213. inputs.clear();
  214. subinputs.clear();
  215. if (memcmp(s, "[]", 2) == 0)
  216. return;
  217. int nscan = 0;
  218. int nconsumed = 0;
  219. int id;
  220. int subid;
  221. int c = 1;// skip leading [
  222. nscan = sscanf(s + c, "[%d, %d%n", &id, &subid, &nconsumed);
  223. while (nscan == 2)
  224. {
  225. inputs.push_back(id);
  226. subinputs.push_back(subid);
  227. // fprintf(stderr, "%d %d\n", id, subid);
  228. c += nconsumed;
  229. nscan = sscanf(s + c, "%*[^[][%d, %d%n", &id, &subid, &nconsumed);
  230. }
  231. }
  232. static bool read_mxnet_json(const char* jsonpath, std::vector<MXNetNode>& nodes)
  233. {
  234. FILE* fp = fopen(jsonpath, "rb");
  235. if (!fp)
  236. {
  237. fprintf(stderr, "fopen %s failed\n", jsonpath);
  238. return false;
  239. }
  240. int internal_unknown = 0;
  241. char line[1024];
  242. //{
  243. (void)fgets(line, 1024, fp);
  244. MXNetNode n;
  245. bool in_nodes_list = false;
  246. bool in_node_block = false;
  247. bool in_attr_block = false;
  248. bool in_inputs_block = false;
  249. while (!feof(fp))
  250. {
  251. char* s = fgets(line, 1024, fp);
  252. if (!s)
  253. break;
  254. if (in_inputs_block)
  255. {
  256. // ]
  257. if (memcmp(line, " ]", 7) == 0)
  258. {
  259. in_inputs_block = false;
  260. continue;
  261. }
  262. // [439, 0, 0],
  263. int id;
  264. int subid;
  265. int nscan = sscanf(line, " [%d, %d", &id, &subid);
  266. if (nscan == 2)
  267. {
  268. n.inputs.push_back(id);
  269. n.subinputs.push_back(subid);
  270. continue;
  271. }
  272. }
  273. if (in_attr_block)
  274. {
  275. // },
  276. if (memcmp(line, " }", 7) == 0)
  277. {
  278. in_attr_block = false;
  279. continue;
  280. }
  281. // replace \" with \$
  282. replace_backslash_doublequote_dollar(line);
  283. // "kernel": "(7,7)",
  284. char key[256] = {0};
  285. char value[256] = {0};
  286. int nscan = sscanf(line, " \"%255[^\"]\": \"%255[^\"]\"", key, value);
  287. if (nscan == 2)
  288. {
  289. n.attrs[key] = value;
  290. // fprintf(stderr, "# %s = %s\n", key, value);
  291. continue;
  292. }
  293. }
  294. if (in_node_block)
  295. {
  296. // },
  297. if (memcmp(line, " }", 5) == 0)
  298. {
  299. // new node
  300. if (n.name.empty())
  301. {
  302. // assign default unknown name
  303. char unknownname[256];
  304. sprintf(unknownname, "unknownncnn_%d", internal_unknown);
  305. n.name = unknownname;
  306. internal_unknown++;
  307. }
  308. nodes.push_back(n);
  309. in_node_block = false;
  310. continue;
  311. }
  312. int nscan;
  313. // "op": "Convolution",
  314. char op[256] = {0};
  315. nscan = sscanf(line, " \"op\": \"%255[^\"]\",", op);
  316. if (nscan == 1)
  317. {
  318. n.op = op;
  319. // fprintf(stderr, "op = %s\n", op);
  320. continue;
  321. }
  322. // "name": "conv0",
  323. char name[256] = {0};
  324. nscan = sscanf(line, " \"name\": \"%255[^\"]\",", name);
  325. if (nscan == 1)
  326. {
  327. n.name = name;
  328. // fprintf(stderr, "name = %s\n", name);
  329. continue;
  330. }
  331. // "inputs": [
  332. if (memcmp(line, " \"inputs\": [\n", 18) == 0)
  333. {
  334. in_inputs_block = true;
  335. continue;
  336. }
  337. // "inputs": []
  338. char inputs[256] = {0};
  339. nscan = sscanf(line, " \"inputs\": %255[^\n]", inputs);
  340. if (nscan == 1)
  341. {
  342. parse_input_list(inputs, n.inputs, n.subinputs);
  343. // fprintf(stderr, "inputs = %s\n", inputs);
  344. continue;
  345. }
  346. // "param": {},
  347. if (memcmp(line, " \"param\": {}", 17) == 0)
  348. {
  349. continue;
  350. }
  351. // replace \" with \$
  352. replace_backslash_doublequote_dollar(line);
  353. // "attr": {"__init__": "[\"zero\", {}]"},
  354. char key[256] = {0};
  355. char value[256] = {0};
  356. nscan = sscanf(line, " \"attr\": {\"%255[^\"]\": \"%255[^\"]\"}", key, value);
  357. if (nscan == 2)
  358. {
  359. n.attrs[key] = value;
  360. // fprintf(stderr, "# %s = %s\n", key, value);
  361. continue;
  362. }
  363. // "attrs": {"__init__": "[\"zero\", {}]"},
  364. nscan = sscanf(line, " \"attrs\": {\"%255[^\"]\": \"%255[^\"]\"}", key, value);
  365. if (nscan == 2)
  366. {
  367. n.attrs[key] = value;
  368. // fprintf(stderr, "# %s = %s\n", key, value);
  369. continue;
  370. }
  371. // "param": {"p": "0.5"},
  372. nscan = sscanf(line, " \"param\": {\"%255[^\"]\": \"%255[^\"]\"}", key, value);
  373. if (nscan == 2)
  374. {
  375. n.attrs[key] = value;
  376. // fprintf(stderr, "# %s = %s\n", key, value);
  377. continue;
  378. }
  379. // "attr": {
  380. if (memcmp(line, " \"attr\": {", 15) == 0)
  381. {
  382. in_attr_block = true;
  383. continue;
  384. }
  385. // "attrs": {
  386. if (memcmp(line, " \"attrs\": {", 16) == 0)
  387. {
  388. in_attr_block = true;
  389. continue;
  390. }
  391. // "param": {
  392. if (memcmp(line, " \"param\": {", 16) == 0)
  393. {
  394. in_attr_block = true;
  395. continue;
  396. }
  397. }
  398. if (in_nodes_list)
  399. {
  400. // ],
  401. if (memcmp(line, " ],", 4) == 0)
  402. {
  403. in_nodes_list = false;
  404. // all nodes parsed
  405. break;
  406. }
  407. // {
  408. if (memcmp(line, " {", 5) == 0)
  409. {
  410. n = MXNetNode();
  411. in_node_block = true;
  412. continue;
  413. }
  414. }
  415. // "nodes": [
  416. if (memcmp(line, " \"nodes\": [", 12) == 0)
  417. {
  418. in_nodes_list = true;
  419. continue;
  420. }
  421. }
  422. fclose(fp);
  423. return true;
  424. }
  425. static bool read_mxnet_param(const char* parampath, std::vector<MXNetParam>& params)
  426. {
  427. FILE* fp = fopen(parampath, "rb");
  428. if (!fp)
  429. {
  430. fprintf(stderr, "fopen %s failed\n", parampath);
  431. return false;
  432. }
  433. uint64_t header;
  434. uint64_t reserved;
  435. fread(&header, 1, sizeof(uint64_t), fp);
  436. fread(&reserved, 1, sizeof(uint64_t), fp);
  437. // NDArray vec
  438. // each data
  439. uint64_t data_count;
  440. fread(&data_count, 1, sizeof(uint64_t), fp);
  441. // fprintf(stderr, "data count = %d\n", (int)data_count);
  442. for (int i = 0; i < (int)data_count; i++)
  443. {
  444. uint32_t magic;// 0xF993FAC9
  445. fread(&magic, 1, sizeof(uint32_t), fp);
  446. // shape
  447. uint32_t ndim;
  448. std::vector<int64_t> shape;
  449. if (magic == 0xF993FAC9)
  450. {
  451. int32_t stype;
  452. fread(&stype, 1, sizeof(int32_t), fp);
  453. fread(&ndim, 1, sizeof(uint32_t), fp);
  454. shape.resize(ndim);
  455. fread(&shape[0], 1, ndim * sizeof(int64_t), fp);
  456. }
  457. else if (magic == 0xF993FAC8)
  458. {
  459. fread(&ndim, 1, sizeof(uint32_t), fp);
  460. shape.resize(ndim);
  461. fread(&shape[0], 1, ndim * sizeof(int64_t), fp);
  462. }
  463. else
  464. {
  465. ndim = magic;
  466. shape.resize(ndim);
  467. std::vector<uint32_t> shape32;
  468. shape32.resize(ndim);
  469. fread(&shape32[0], 1, ndim * sizeof(uint32_t), fp);
  470. for (int j=0; j<(int)ndim; j++)
  471. {
  472. shape[j] = shape32[j];
  473. }
  474. }
  475. // context
  476. int32_t dev_type;
  477. int32_t dev_id;
  478. fread(&dev_type, 1, sizeof(int32_t), fp);
  479. fread(&dev_id, 1, sizeof(int32_t), fp);
  480. int32_t type_flag;
  481. fread(&type_flag, 1, sizeof(int32_t), fp);
  482. // data
  483. size_t len = 0;
  484. if (shape.size() == 1) len = shape[0];
  485. if (shape.size() == 2) len = shape[0] * shape[1];
  486. if (shape.size() == 3) len = shape[0] * shape[1] * shape[2];
  487. if (shape.size() == 4) len = shape[0] * shape[1] * shape[2] * shape[3];
  488. MXNetParam p;
  489. p.data.resize(len);
  490. fread(&p.data[0], 1, len * sizeof(float), fp);
  491. params.push_back(p);
  492. // fprintf(stderr, "%u read\n", len);
  493. }
  494. // each name
  495. uint64_t name_count;
  496. fread(&name_count, 1, sizeof(uint64_t), fp);
  497. // fprintf(stderr, "name count = %d\n", (int)name_count);
  498. for (int i = 0; i < (int)name_count; i++)
  499. {
  500. uint64_t len;
  501. fread(&len, 1, sizeof(uint64_t), fp);
  502. MXNetParam& p = params[i];
  503. p.name.resize(len);
  504. fread((char*)p.name.data(), 1, len, fp);
  505. // cut leading arg:
  506. if (memcmp(p.name.c_str(), "arg:", 4) == 0)
  507. {
  508. p.name = std::string(p.name.c_str() + 4);
  509. }
  510. if (memcmp(p.name.c_str(), "aux:", 4) == 0)
  511. {
  512. p.name = std::string(p.name.c_str() + 4);
  513. }
  514. // fprintf(stderr, "%s read\n", p.name.c_str());
  515. }
  516. fclose(fp);
  517. return true;
  518. }
  519. int main(int argc, char** argv)
  520. {
  521. const char* jsonpath = argv[1];
  522. const char* parampath = argv[2];
  523. const char* ncnn_prototxt = argc >= 5 ? argv[3] : "ncnn.param";
  524. const char* ncnn_modelbin = argc >= 5 ? argv[4] : "ncnn.bin";
  525. std::vector<MXNetNode> nodes;
  526. std::vector<MXNetParam> params;
  527. read_mxnet_json(jsonpath, nodes);
  528. read_mxnet_param(parampath, params);
  529. FILE* pp = fopen(ncnn_prototxt, "wb");
  530. FILE* bp = fopen(ncnn_modelbin, "wb");
  531. // magic
  532. fprintf(pp, "7767517\n");
  533. int node_count = nodes.size();
  534. // node reference
  535. std::map<int, int> node_reference;
  536. // weight node
  537. std::vector<int> weight_nodes;
  538. // global definition line
  539. // [layer count] [blob count]
  540. std::set<std::string> blob_names;
  541. for (int i=0; i<node_count; i++)
  542. {
  543. MXNetNode& n = nodes[i];
  544. // assign global param reference
  545. n.nodes = &nodes;
  546. n.params = &params;
  547. const std::string& output_name = n.name;
  548. n.output_size = 1;
  549. if (n.op == "null")
  550. {
  551. if (n.is_weight())
  552. {
  553. weight_nodes.push_back(i);
  554. }
  555. else
  556. {
  557. if (n.has_attr("__init__"))
  558. {
  559. // init weight param
  560. MXNetParam pi;
  561. pi.name = n.name;
  562. pi.init = (std::string)n.attr("__init__");
  563. params.push_back(pi);
  564. weight_nodes.push_back(i);
  565. }
  566. else
  567. {
  568. // null node without data, treat it as network input
  569. }
  570. }
  571. continue;
  572. }
  573. else if (n.op == "_contrib_MultiBoxTarget")
  574. {
  575. n.output_size = 3;
  576. }
  577. else if (n.op == "SliceChannel")
  578. {
  579. n.output_size = n.attr("num_outputs");
  580. }
  581. // distinguish weights and inputs
  582. std::vector<int> weights;
  583. std::vector<int> inputs;
  584. for (int j=0; j<(int)n.inputs.size(); j++)
  585. {
  586. int input_index = n.inputs[j];
  587. if (nodes[input_index].is_weight())
  588. {
  589. weights.push_back(input_index);
  590. continue;
  591. }
  592. inputs.push_back(input_index);
  593. }
  594. n.inputs = inputs;
  595. n.weights = weights;
  596. if (n.op == "_contrib_MultiBoxDetection")
  597. {
  598. // reorder input blob
  599. int temp = n.inputs[0];
  600. n.inputs[0] = n.inputs[1];
  601. n.inputs[1] = temp;
  602. }
  603. // input
  604. for (int j=0; j<(int)n.inputs.size(); j++)
  605. {
  606. int input_index = n.inputs[j];
  607. int subinput_index = n.subinputs[j];
  608. std::string input_name = nodes[input_index].name;
  609. // fprintf(stderr, "input = %s\n", input_name.c_str());
  610. if (subinput_index != 0)
  611. {
  612. char subinputsuffix[256];
  613. sprintf(subinputsuffix, "_subncnn_%d", subinput_index);
  614. input_name = input_name + subinputsuffix;
  615. }
  616. blob_names.insert(input_name);
  617. int input_uid = input_index | (subinput_index << 16);
  618. if (node_reference.find(input_uid) == node_reference.end())
  619. {
  620. node_reference[input_uid] = 1;
  621. }
  622. else
  623. {
  624. node_reference[input_uid] = node_reference[input_uid] + 1;
  625. }
  626. }
  627. // output
  628. // fprintf(stderr, "output = %s\n", output_name.c_str());
  629. blob_names.insert(output_name);
  630. for (int j=1; j<n.output_size; j++)
  631. {
  632. char subinputsuffix[256];
  633. sprintf(subinputsuffix, "_%d", j);
  634. std::string output_name_j = output_name + subinputsuffix;
  635. blob_names.insert(output_name_j);
  636. }
  637. }
  638. // for (std::map<int, int>::iterator it = node_reference.begin(); it != node_reference.end(); it++)
  639. // {
  640. // fprintf(stderr, "ref %d %d\n", it->first, it->second);
  641. // }
  642. // op chain fusion
  643. int reduced_node_count = 0;
  644. for (int i=0; i<node_count; i++)
  645. {
  646. const MXNetNode& n = nodes[i];
  647. if (n.is_weight())
  648. continue;
  649. // ShuffleChannel <= Reshape - SwapAxis - Reshape
  650. if (n.op == "Reshape")
  651. {
  652. if (node_reference[i] != 1)
  653. continue;
  654. // "shape": "(0, -4, X, -1, -2)"
  655. std::vector<int> shape = n.attr("shape");
  656. if (shape.size() != 5)
  657. continue;
  658. if (shape[0] != 0 || shape[1] != -4 || shape[3] != -1 || shape[4] != -2)
  659. continue;
  660. if (i+2 >= node_count)
  661. continue;
  662. const MXNetNode& n2 = nodes[i+1];
  663. const MXNetNode& n3 = nodes[i+2];
  664. if (n2.op != "SwapAxis" || n3.op != "Reshape")
  665. continue;
  666. if (node_reference[i+1] != 1)
  667. continue;
  668. // "dim1": "1", "dim2": "2"
  669. int dim1 = n2.attr("dim1");
  670. int dim2 = n2.attr("dim2");
  671. if (dim1 != 1 || dim2 != 2)
  672. continue;
  673. // "shape": "(0, -3, -2)"
  674. std::vector<int> shape3 = n3.attr("shape");
  675. if (shape3.size() != 3)
  676. continue;
  677. if (shape3[0] != 0 || shape3[1] != -3 || shape3[2] != -2)
  678. continue;
  679. // reduce
  680. nodes[i].op = "noop_reducedncnn";
  681. nodes[i+1].op = "noop_reducedncnn";
  682. node_reference.erase(node_reference.find(i));
  683. node_reference.erase(node_reference.find(i+1));
  684. blob_names.erase(n.name);
  685. blob_names.erase(n2.name);
  686. MXNetNode new_node;
  687. new_node.nodes = &nodes;
  688. new_node.params = &params;
  689. new_node.op = "ShuffleChannel";
  690. // new_node.name = n.name + "_" + n2.name + "_" + n3.name;
  691. new_node.name = n3.name;
  692. new_node.output_size = n3.output_size;
  693. char group[16];
  694. sprintf(group, "%d", shape[2]);
  695. new_node.attrs["group"] = group;
  696. new_node.inputs = n.inputs;
  697. new_node.subinputs = n.subinputs;
  698. nodes[i+2] = new_node;
  699. reduced_node_count += 2;
  700. i += 2;
  701. }
  702. }
  703. // remove node_reference entry with reference equals to one
  704. int splitncnn_blob_count = 0;
  705. std::map<int, int>::iterator it = node_reference.begin();
  706. while (it != node_reference.end())
  707. {
  708. if (it->second == 1)
  709. {
  710. node_reference.erase(it++);
  711. }
  712. else
  713. {
  714. splitncnn_blob_count += it->second;
  715. // fprintf(stderr, "%s %d\n", it->first.c_str(), it->second);
  716. ++it;
  717. }
  718. }
  719. // fprintf(stderr, "%d %d %d %d, %d %d\n", node_count, reduced_node_count, node_reference.size(), weight_nodes.size(), blob_names.size(), splitncnn_blob_count);
  720. fprintf(pp, "%lu %lu\n", node_count - reduced_node_count + node_reference.size() - weight_nodes.size(), blob_names.size() + splitncnn_blob_count);
  721. int internal_split = 0;
  722. for (int i=0; i<node_count; i++)
  723. {
  724. const MXNetNode& n = nodes[i];
  725. if (n.op == "noop_reducedncnn")
  726. {
  727. continue;
  728. }
  729. if (n.op == "null")
  730. {
  731. if (n.is_weight())
  732. {
  733. continue;
  734. }
  735. fprintf(pp, "%-16s", "Input");
  736. }
  737. else if (n.op == "_contrib_MultiBoxDetection")
  738. {
  739. fprintf(pp, "%-16s", "DetectionOutput");
  740. }
  741. else if (n.op == "_contrib_MultiBoxPrior")
  742. {
  743. fprintf(pp, "%-16s", "PriorBox");
  744. }
  745. else if (n.op == "_div_scalar")
  746. {
  747. fprintf(pp, "%-16s", "BinaryOp");
  748. }
  749. else if (n.op == "_maximum_scalar")
  750. {
  751. fprintf(pp, "%-16s", "BinaryOp");
  752. }
  753. else if (n.op == "_minimum_scalar")
  754. {
  755. fprintf(pp, "%-16s", "BinaryOp");
  756. }
  757. else if (n.op == "_minus_scalar")
  758. {
  759. fprintf(pp, "%-16s", "BinaryOp");
  760. }
  761. else if (n.op == "_mul_scalar")
  762. {
  763. fprintf(pp, "%-16s", "BinaryOp");
  764. }
  765. else if (n.op == "_plus_scalar")
  766. {
  767. fprintf(pp, "%-16s", "BinaryOp");
  768. }
  769. else if (n.op == "_power_scalar")
  770. {
  771. fprintf(pp, "%-16s", "BinaryOp");
  772. }
  773. else if (n.op == "_rdiv_scalar")
  774. {
  775. fprintf(pp, "%-16s", "BinaryOp");
  776. }
  777. else if (n.op == "_rminus_scalar")
  778. {
  779. fprintf(pp, "%-16s", "BinaryOp");
  780. }
  781. else if (n.op == "abs")
  782. {
  783. fprintf(pp, "%-16s", "UnaryOp");
  784. }
  785. else if (n.op == "Activation")
  786. {
  787. std::string type = n.attr("act_type");
  788. if (type == "relu")
  789. {
  790. fprintf(pp, "%-16s", "ReLU");
  791. }
  792. else if (type == "sigmoid")
  793. {
  794. fprintf(pp, "%-16s", "Sigmoid");
  795. }
  796. else if (type == "tanh")
  797. {
  798. fprintf(pp, "%-16s", "TanH");
  799. }
  800. }
  801. else if (n.op == "arccos")
  802. {
  803. fprintf(pp, "%-16s", "UnaryOp");
  804. }
  805. else if (n.op == "arcsin")
  806. {
  807. fprintf(pp, "%-16s", "UnaryOp");
  808. }
  809. else if (n.op == "arctan")
  810. {
  811. fprintf(pp, "%-16s", "UnaryOp");
  812. }
  813. else if (n.op == "BatchNorm")
  814. {
  815. fprintf(pp, "%-16s", "BatchNorm");
  816. }
  817. else if (n.op == "broadcast_add")
  818. {
  819. fprintf(pp, "%-16s", "BinaryOp");
  820. }
  821. else if (n.op == "broadcast_div")
  822. {
  823. fprintf(pp, "%-16s", "BinaryOp");
  824. }
  825. else if (n.op == "broadcast_mul")
  826. {
  827. fprintf(pp, "%-16s", "BinaryOp");
  828. }
  829. else if (n.op == "broadcast_sub")
  830. {
  831. fprintf(pp, "%-16s", "BinaryOp");
  832. }
  833. else if (n.op == "ceil")
  834. {
  835. fprintf(pp, "%-16s", "UnaryOp");
  836. }
  837. else if (n.op == "clip")
  838. {
  839. fprintf(pp, "%-16s", "Clip");
  840. }
  841. else if (n.op == "Concat")
  842. {
  843. fprintf(pp, "%-16s", "Concat");
  844. }
  845. else if (n.op == "Convolution")
  846. {
  847. int num_group = n.attr("num_group");
  848. if (num_group > 1) {
  849. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  850. } else {
  851. fprintf(pp, "%-16s", "Convolution");
  852. }
  853. }
  854. else if (n.op == "cos")
  855. {
  856. fprintf(pp, "%-16s", "UnaryOp");
  857. }
  858. else if (n.op == "Crop")
  859. {
  860. fprintf(pp, "%-16s", "Crop");
  861. }
  862. else if (n.op == "Deconvolution")
  863. {
  864. int num_group = n.attr("num_group");
  865. if (num_group > 1) {
  866. fprintf(pp, "%-16s", "DeconvolutionDepthWise");
  867. } else {
  868. fprintf(pp, "%-16s", "Deconvolution");
  869. }
  870. }
  871. else if (n.op == "Dropout")
  872. {
  873. fprintf(pp, "%-16s", "Dropout");
  874. }
  875. else if (n.op == "elemwise_add")
  876. {
  877. fprintf(pp, "%-16s", "BinaryOp");
  878. }
  879. else if (n.op == "elemwise_div")
  880. {
  881. fprintf(pp, "%-16s", "BinaryOp");
  882. }
  883. else if (n.op == "elemwise_mul")
  884. {
  885. fprintf(pp, "%-16s", "BinaryOp");
  886. }
  887. else if (n.op == "elemwise_sub")
  888. {
  889. fprintf(pp, "%-16s", "BinaryOp");
  890. }
  891. else if (n.op == "Embedding")
  892. {
  893. fprintf(pp, "%-16s", "Embed");
  894. }
  895. else if (n.op == "exp")
  896. {
  897. fprintf(pp, "%-16s", "UnaryOp");
  898. }
  899. else if (n.op == "expand_dims")
  900. {
  901. fprintf(pp, "%-16s", "ExpandDims");
  902. }
  903. else if (n.op == "Flatten")
  904. {
  905. fprintf(pp, "%-16s", "Flatten");
  906. }
  907. else if (n.op == "floor")
  908. {
  909. fprintf(pp, "%-16s", "UnaryOp");
  910. }
  911. else if (n.op == "FullyConnected")
  912. {
  913. fprintf(pp, "%-16s", "InnerProduct");
  914. }
  915. else if (n.op == "InstanceNorm")
  916. {
  917. fprintf(pp, "%-16s", "InstanceNorm");
  918. }
  919. else if (n.op == "L2Normalization")
  920. {
  921. fprintf(pp, "%-16s", "Normalize");
  922. }
  923. else if (n.op == "LeakyReLU")
  924. {
  925. std::string type = n.attr("act_type");
  926. if (type == "elu")
  927. {
  928. fprintf(pp, "%-16s", "ELU");
  929. }
  930. else if (type == "leaky" || type.empty())
  931. {
  932. fprintf(pp, "%-16s", "ReLU");
  933. }
  934. else if (type == "prelu")
  935. {
  936. fprintf(pp, "%-16s", "PReLU");
  937. }
  938. }
  939. else if (n.op == "log")
  940. {
  941. fprintf(pp, "%-16s", "UnaryOp");
  942. }
  943. else if (n.op == "LogisticRegressionOutput")
  944. {
  945. fprintf(pp, "%-16s", "Sigmoid");
  946. }
  947. else if (n.op == "max")
  948. {
  949. fprintf(pp, "%-16s", "Reduction");
  950. }
  951. else if (n.op == "maximum")
  952. {
  953. fprintf(pp, "%-16s", "BinaryOp");
  954. }
  955. else if (n.op == "mean")
  956. {
  957. fprintf(pp, "%-16s", "Reduction");
  958. }
  959. else if (n.op == "min")
  960. {
  961. fprintf(pp, "%-16s", "Reduction");
  962. }
  963. else if (n.op == "minimum")
  964. {
  965. fprintf(pp, "%-16s", "BinaryOp");
  966. }
  967. else if (n.op == "negative")
  968. {
  969. fprintf(pp, "%-16s", "UnaryOp");
  970. }
  971. else if (n.op == "Pad")
  972. {
  973. fprintf(pp, "%-16s", "Padding");
  974. }
  975. else if (n.op == "Pooling")
  976. {
  977. fprintf(pp, "%-16s", "Pooling");
  978. }
  979. else if (n.op == "prod")
  980. {
  981. fprintf(pp, "%-16s", "Reduction");
  982. }
  983. else if (n.op == "reciprocal")
  984. {
  985. fprintf(pp, "%-16s", "UnaryOp");
  986. }
  987. else if (n.op == "relu")
  988. {
  989. fprintf(pp, "%-16s", "ReLU");
  990. }
  991. else if (n.op == "Reshape")
  992. {
  993. fprintf(pp, "%-16s", "Reshape");
  994. }
  995. else if (n.op == "ShuffleChannel")
  996. {
  997. fprintf(pp, "%-16s", "ShuffleChannel");
  998. }
  999. else if (n.op == "sigmoid")
  1000. {
  1001. fprintf(pp, "%-16s", "Sigmoid");
  1002. }
  1003. else if (n.op == "sin")
  1004. {
  1005. fprintf(pp, "%-16s", "UnaryOp");
  1006. }
  1007. else if (n.op == "slice")
  1008. {
  1009. fprintf(pp, "%-16s", "Crop");
  1010. }
  1011. else if (n.op == "SliceChannel")
  1012. {
  1013. fprintf(pp, "%-16s", "Slice");
  1014. }
  1015. else if (n.op == "SoftmaxActivation")
  1016. {
  1017. fprintf(pp, "%-16s", "Softmax");
  1018. }
  1019. else if (n.op == "SoftmaxOutput")
  1020. {
  1021. fprintf(pp, "%-16s", "Softmax");
  1022. }
  1023. else if (n.op == "sqrt")
  1024. {
  1025. fprintf(pp, "%-16s", "UnaryOp");
  1026. }
  1027. else if (n.op == "square")
  1028. {
  1029. fprintf(pp, "%-16s", "UnaryOp");
  1030. }
  1031. else if (n.op == "sum")
  1032. {
  1033. fprintf(pp, "%-16s", "Reduction");
  1034. }
  1035. else if (n.op == "tan")
  1036. {
  1037. fprintf(pp, "%-16s", "UnaryOp");
  1038. }
  1039. else if (n.op == "tanh")
  1040. {
  1041. fprintf(pp, "%-16s", "TanH");
  1042. }
  1043. else if (n.op == "Transpose" || n.op == "transpose")
  1044. {
  1045. fprintf(pp, "%-16s", "Permute");
  1046. }
  1047. else if (n.op == "UpSampling")
  1048. {
  1049. std::string sample_type = n.attr("sample_type");
  1050. if (sample_type == "nearest")
  1051. {
  1052. fprintf(pp, "%-16s", "Interp");
  1053. }
  1054. else if (sample_type == "bilinear")
  1055. {
  1056. fprintf(pp, "%-16s", "DeconvolutionDepthWise");
  1057. }
  1058. }
  1059. else
  1060. {
  1061. fprintf(stderr, "%s not supported yet!\n", n.op.c_str());
  1062. fprintf(pp, "%-16s", n.op.c_str());
  1063. }
  1064. int input_size = n.inputs.size();
  1065. for (int j=0; j<(int)n.inputs.size(); j++)
  1066. {
  1067. int input_index = n.inputs[j];
  1068. if (nodes[input_index].is_weight())
  1069. {
  1070. input_size--;
  1071. }
  1072. }
  1073. if (n.op == "SoftmaxOutput" || n.op == "LogisticRegressionOutput")
  1074. {
  1075. // drop label
  1076. input_size--;
  1077. }
  1078. fprintf(pp, " %-32s %d %d", n.name.c_str(), input_size, n.output_size);
  1079. for (int j=0; j<(int)n.inputs.size(); j++)
  1080. {
  1081. int input_index = n.inputs[j];
  1082. int subinput_index = n.subinputs[j];
  1083. if (nodes[input_index].is_weight())
  1084. {
  1085. continue;
  1086. }
  1087. if (n.op == "SoftmaxOutput" || n.op == "LogisticRegressionOutput")
  1088. {
  1089. // drop label
  1090. if (j == 1)
  1091. continue;
  1092. }
  1093. std::string input_name = nodes[input_index].name;
  1094. if (subinput_index != 0)
  1095. {
  1096. char subinputsuffix[256];
  1097. sprintf(subinputsuffix, "_subncnn_%d", subinput_index);
  1098. input_name = input_name + subinputsuffix;
  1099. }
  1100. int input_uid = input_index | (subinput_index << 16);
  1101. if (node_reference.find(input_uid) != node_reference.end())
  1102. {
  1103. int refidx = node_reference[input_uid] - 1;
  1104. node_reference[input_uid] = refidx;
  1105. char splitsuffix[256];
  1106. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  1107. input_name = input_name + splitsuffix;
  1108. }
  1109. fprintf(pp, " %s", input_name.c_str());
  1110. }
  1111. fprintf(pp, " %s", n.name.c_str());
  1112. for (int j=1; j<n.output_size; j++)
  1113. {
  1114. fprintf(pp, " %s_subncnn_%d", n.name.c_str(), j);
  1115. }
  1116. if (n.op == "null")
  1117. {
  1118. // dummy input shape
  1119. // fprintf(pp, " 0 0 0");
  1120. }
  1121. else if (n.op == "_contrib_MultiBoxDetection")
  1122. {
  1123. float threshold = n.has_attr("threshold") ? n.attr("threshold") : 0.01f;
  1124. float nms_threshold = n.has_attr("nms_threshold") ? n.attr("nms_threshold") : 0.5f;
  1125. int nms_topk = n.has_attr("nms_topk") ? n.attr("nms_topk") : 300;
  1126. fprintf(pp, " 0=-233");
  1127. fprintf(pp, " 1=%f", nms_threshold);
  1128. fprintf(pp, " 2=%d", nms_topk);
  1129. int keep_top_k = 100;
  1130. fprintf(pp, " 3=%d", keep_top_k);
  1131. fprintf(pp, " 4=%f", threshold);
  1132. std::vector<float> variances = n.attr("variances");
  1133. if (variances.empty())
  1134. {
  1135. fprintf(pp, " 5=0.1");
  1136. fprintf(pp, " 6=0.1");
  1137. fprintf(pp, " 7=0.2");
  1138. fprintf(pp, " 8=0.2");
  1139. }
  1140. else
  1141. {
  1142. fprintf(pp, " 5=%f", variances[0]);
  1143. fprintf(pp, " 6=%f", variances[1]);
  1144. fprintf(pp, " 7=%f", variances[2]);
  1145. fprintf(pp, " 8=%f", variances[3]);
  1146. }
  1147. }
  1148. else if (n.op == "_contrib_MultiBoxPrior")
  1149. {
  1150. // mxnet-ssd encode size as scale factor, fill min_size
  1151. std::vector<float> sizes = n.attr("sizes");
  1152. fprintf(pp, " -23300=%d", (int)sizes.size());
  1153. for (int j=0; j<(int)sizes.size(); j++)
  1154. {
  1155. fprintf(pp, ",%f", sizes[j]);
  1156. }
  1157. std::vector<float> aspect_ratios = n.attr("ratios");
  1158. fprintf(pp, " -23302=%d", (int)aspect_ratios.size());
  1159. for (int j=0; j<(int)aspect_ratios.size(); j++)
  1160. {
  1161. fprintf(pp, ",%f", aspect_ratios[j]);
  1162. }
  1163. int flip = 0;
  1164. fprintf(pp, " 7=%d", flip);
  1165. int clip = n.attr("clip");
  1166. fprintf(pp, " 8=%d", clip);
  1167. // auto image size
  1168. fprintf(pp, " 9=-233");
  1169. fprintf(pp, " 10=-233");
  1170. std::vector<float> steps = n.attr("steps");
  1171. if (steps.empty() || (steps[0] == -1.f && steps[1] == -1.f))
  1172. {
  1173. // auto step
  1174. fprintf(pp, " 11=-233.0");
  1175. fprintf(pp, " 12=-233.0");
  1176. }
  1177. else
  1178. {
  1179. fprintf(stderr, "Unsupported steps param! %f %f\n", steps[0], steps[1]);
  1180. }
  1181. std::vector<float> offsets = n.attr("offsets");
  1182. if (offsets.empty() || (offsets[0] == 0.5f && offsets[1] == 0.5f))
  1183. {
  1184. fprintf(pp, " 13=0.5");
  1185. }
  1186. else
  1187. {
  1188. fprintf(stderr, "Unsupported offsets param! %f %f\n", offsets[0], offsets[1]);
  1189. }
  1190. }
  1191. else if (n.op == "_div_scalar")
  1192. {
  1193. int op_type = 3;
  1194. int with_scalar = 1;
  1195. float scalar = n.attr("scalar");
  1196. fprintf(pp, " 0=%d", op_type);
  1197. fprintf(pp, " 1=%d", with_scalar);
  1198. fprintf(pp, " 2=%f", scalar);
  1199. }
  1200. else if (n.op == "_maximum_scalar")
  1201. {
  1202. int op_type = 4;
  1203. int with_scalar = 1;
  1204. float scalar = n.attr("scalar");
  1205. fprintf(pp, " 0=%d", op_type);
  1206. fprintf(pp, " 1=%d", with_scalar);
  1207. fprintf(pp, " 2=%f", scalar);
  1208. }
  1209. else if (n.op == "_minimum_scalar")
  1210. {
  1211. int op_type = 5;
  1212. int with_scalar = 1;
  1213. float scalar = n.attr("scalar");
  1214. fprintf(pp, " 0=%d", op_type);
  1215. fprintf(pp, " 1=%d", with_scalar);
  1216. fprintf(pp, " 2=%f", scalar);
  1217. }
  1218. else if (n.op == "_minus_scalar")
  1219. {
  1220. int op_type = 1;
  1221. int with_scalar = 1;
  1222. float scalar = n.attr("scalar");
  1223. fprintf(pp, " 0=%d", op_type);
  1224. fprintf(pp, " 1=%d", with_scalar);
  1225. fprintf(pp, " 2=%f", scalar);
  1226. }
  1227. else if (n.op == "_mul_scalar")
  1228. {
  1229. int op_type = 2;
  1230. int with_scalar = 1;
  1231. float scalar = n.attr("scalar");
  1232. fprintf(pp, " 0=%d", op_type);
  1233. fprintf(pp, " 1=%d", with_scalar);
  1234. fprintf(pp, " 2=%f", scalar);
  1235. }
  1236. else if (n.op == "_plus_scalar")
  1237. {
  1238. int op_type = 0;
  1239. int with_scalar = 1;
  1240. float scalar = n.attr("scalar");
  1241. fprintf(pp, " 0=%d", op_type);
  1242. fprintf(pp, " 1=%d", with_scalar);
  1243. fprintf(pp, " 2=%f", scalar);
  1244. }
  1245. else if (n.op == "_power_scalar")
  1246. {
  1247. int op_type = 6;
  1248. int with_scalar = 1;
  1249. float scalar = n.attr("scalar");
  1250. fprintf(pp, " 0=%d", op_type);
  1251. fprintf(pp, " 1=%d", with_scalar);
  1252. fprintf(pp, " 2=%f", scalar);
  1253. }
  1254. else if (n.op == "_rdiv_scalar")
  1255. {
  1256. int op_type = 8;
  1257. int with_scalar = 1;
  1258. float scalar = n.attr("scalar");
  1259. fprintf(pp, " 0=%d", op_type);
  1260. fprintf(pp, " 1=%d", with_scalar);
  1261. fprintf(pp, " 2=%f", scalar);
  1262. }
  1263. else if (n.op == "_rminus_scalar")
  1264. {
  1265. int op_type = 7;
  1266. int with_scalar = 1;
  1267. float scalar = n.attr("scalar");
  1268. fprintf(pp, " 0=%d", op_type);
  1269. fprintf(pp, " 1=%d", with_scalar);
  1270. fprintf(pp, " 2=%f", scalar);
  1271. }
  1272. else if (n.op == "abs")
  1273. {
  1274. int op_type = 0;
  1275. fprintf(pp, " 0=%d", op_type);
  1276. }
  1277. else if (n.op == "Activation")
  1278. {
  1279. std::string type = n.attr("act_type");
  1280. if (type == "relu")
  1281. {
  1282. // fprintf(pp, " 0=%f", 0.f);
  1283. }
  1284. }
  1285. else if (n.op == "arccos")
  1286. {
  1287. int op_type = 13;
  1288. fprintf(pp, " 0=%d", op_type);
  1289. }
  1290. else if (n.op == "arcsin")
  1291. {
  1292. int op_type = 12;
  1293. fprintf(pp, " 0=%d", op_type);
  1294. }
  1295. else if (n.op == "arctan")
  1296. {
  1297. int op_type = 14;
  1298. fprintf(pp, " 0=%d", op_type);
  1299. }
  1300. else if (n.op == "BatchNorm")
  1301. {
  1302. float eps = 1e-3;
  1303. if (n.has_attr("eps")) {
  1304. eps = n.attr("eps");
  1305. }
  1306. std::vector<float> slope_data = n.weight(0);
  1307. std::vector<float> bias_data = n.weight(1);
  1308. int channels = slope_data.size();
  1309. std::vector<float> mean_data = n.weight(2, channels);
  1310. std::vector<float> var_data = n.weight(3, channels);
  1311. for (int j=0; j<(int)var_data.size(); j++)
  1312. {
  1313. var_data[j] += eps;
  1314. }
  1315. fprintf(pp, " 0=%d", channels);
  1316. int fix_gamma = n.has_attr("fix_gamma") ? n.attr("fix_gamma") : 0;
  1317. if (fix_gamma)
  1318. {
  1319. // slope data are all 0 here, force set 1
  1320. for (int j=0; j<channels; j++)
  1321. {
  1322. slope_data[j] = 1.f;
  1323. }
  1324. }
  1325. fwrite(slope_data.data(), sizeof(float), slope_data.size(), bp);
  1326. fwrite(mean_data.data(), sizeof(float), mean_data.size(), bp);
  1327. fwrite(var_data.data(), sizeof(float), var_data.size(), bp);
  1328. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1329. }
  1330. else if (n.op == "broadcast_add")
  1331. {
  1332. int op_type = 0;
  1333. fprintf(pp, " 0=%d", op_type);
  1334. }
  1335. else if (n.op == "broadcast_div")
  1336. {
  1337. int op_type = 3;
  1338. fprintf(pp, " 0=%d", op_type);
  1339. }
  1340. else if (n.op == "broadcast_mul")
  1341. {
  1342. int op_type = 2;
  1343. fprintf(pp, " 0=%d", op_type);
  1344. }
  1345. else if (n.op == "broadcast_sub")
  1346. {
  1347. int op_type = 1;
  1348. fprintf(pp, " 0=%d", op_type);
  1349. }
  1350. else if (n.op == "ceil")
  1351. {
  1352. int op_type = 3;
  1353. fprintf(pp, " 0=%d", op_type);
  1354. }
  1355. else if (n.op == "clip")
  1356. {
  1357. float min = n.attr("a_min");
  1358. float max = n.attr("a_max");
  1359. fprintf(pp, " 0=%f", min);
  1360. fprintf(pp, " 1=%f", max);
  1361. }
  1362. else if (n.op == "Concat")
  1363. {
  1364. int dim = n.has_attr("dim") ? n.attr("dim") : 1;
  1365. fprintf(pp, " 0=%d", dim-1);
  1366. }
  1367. else if (n.op == "Convolution")
  1368. {
  1369. int num_filter = n.attr("num_filter");
  1370. std::vector<int> kernel = n.attr("kernel");
  1371. std::vector<int> dilate = n.attr("dilate");
  1372. std::vector<int> stride = n.attr("stride");
  1373. std::vector<int> pad = n.attr("pad");
  1374. int no_bias = n.attr("no_bias");
  1375. int num_group = n.attr("num_group");
  1376. std::vector<float> weight_data = n.weight(0);
  1377. std::vector<float> bias_data = n.weight(1);
  1378. fprintf(pp, " 0=%d", num_filter);
  1379. if (kernel.size() == 1) {
  1380. fprintf(pp, " 1=%d", kernel[0]);
  1381. } else if (kernel.size() == 2) {
  1382. fprintf(pp, " 1=%d", kernel[1]);
  1383. fprintf(pp, " 11=%d", kernel[0]);
  1384. }
  1385. if (dilate.size() == 1) {
  1386. fprintf(pp, " 2=%d", dilate[0]);
  1387. } else if (dilate.size() == 2) {
  1388. fprintf(pp, " 2=%d", dilate[1]);
  1389. fprintf(pp, " 12=%d", dilate[0]);
  1390. }
  1391. if (stride.size() == 1) {
  1392. fprintf(pp, " 3=%d", stride[0]);
  1393. } else if (stride.size() == 2) {
  1394. fprintf(pp, " 3=%d", stride[1]);
  1395. fprintf(pp, " 13=%d", stride[0]);
  1396. }
  1397. if (pad.size() == 1) {
  1398. fprintf(pp, " 4=%d", pad[0]);
  1399. } else if (pad.size() == 2) {
  1400. fprintf(pp, " 4=%d", pad[1]);
  1401. fprintf(pp, " 14=%d", pad[0]);
  1402. }
  1403. fprintf(pp, " 5=%d", no_bias == 1 ? 0 : 1);
  1404. fprintf(pp, " 6=%d", (int)weight_data.size());
  1405. if (num_group > 1) {
  1406. fprintf(pp, " 7=%d", num_group);
  1407. }
  1408. int quantize_tag = 0;
  1409. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1410. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1411. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1412. }
  1413. else if (n.op == "Deconvolution")
  1414. {
  1415. int num_filter = n.attr("num_filter");
  1416. std::vector<int> kernel = n.attr("kernel");
  1417. std::vector<int> dilate = n.attr("dilate");
  1418. std::vector<int> stride = n.attr("stride");
  1419. std::vector<int> pad = n.attr("pad");
  1420. int no_bias = n.attr("no_bias");
  1421. int num_group = n.attr("num_group");
  1422. std::vector<float> weight_data = n.weight(0);
  1423. std::vector<float> bias_data = n.weight(1);
  1424. fprintf(pp, " 0=%d", num_filter);
  1425. if (kernel.size() == 1) {
  1426. fprintf(pp, " 1=%d", kernel[0]);
  1427. } else if (kernel.size() == 2) {
  1428. fprintf(pp, " 1=%d", kernel[1]);
  1429. fprintf(pp, " 11=%d", kernel[0]);
  1430. }
  1431. if (dilate.size() == 1) {
  1432. fprintf(pp, " 2=%d", dilate[0]);
  1433. } else if (dilate.size() == 2) {
  1434. fprintf(pp, " 2=%d", dilate[1]);
  1435. fprintf(pp, " 12=%d", dilate[0]);
  1436. }
  1437. if (stride.size() == 1) {
  1438. fprintf(pp, " 3=%d", stride[0]);
  1439. } else if (stride.size() == 2) {
  1440. fprintf(pp, " 3=%d", stride[1]);
  1441. fprintf(pp, " 13=%d", stride[0]);
  1442. }
  1443. if (pad.size() == 1) {
  1444. fprintf(pp, " 4=%d", pad[0]);
  1445. } else if (pad.size() == 2) {
  1446. fprintf(pp, " 4=%d", pad[1]);
  1447. fprintf(pp, " 14=%d", pad[0]);
  1448. }
  1449. fprintf(pp, " 5=%d", no_bias == 1 ? 0 : 1);
  1450. fprintf(pp, " 6=%d", (int)weight_data.size());
  1451. if (num_group > 1) {
  1452. fprintf(pp, " 7=%d", num_group);
  1453. }
  1454. int quantize_tag = 0;
  1455. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1456. int maxk = 0;
  1457. if (kernel.size() == 2)
  1458. {
  1459. maxk = kernel[1] * kernel[0];
  1460. }
  1461. else
  1462. {
  1463. maxk = kernel[0] * kernel[0];
  1464. }
  1465. for (int g=0; g<num_group; g++)
  1466. {
  1467. // reorder weight from inch-outch to outch-inch
  1468. int num_filter_g = num_filter / num_group;
  1469. int num_input = weight_data.size() / maxk / num_filter_g / num_group;
  1470. const float* weight_data_ptr = weight_data.data() + g * maxk * num_filter_g * num_input;
  1471. for (int k=0; k<num_filter_g; k++)
  1472. {
  1473. for (int j=0; j<num_input; j++)
  1474. {
  1475. fwrite(weight_data_ptr + (j*num_filter_g + k) * maxk, sizeof(float), maxk, bp);
  1476. }
  1477. }
  1478. }
  1479. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1480. }
  1481. else if (n.op == "cos")
  1482. {
  1483. int op_type = 10;
  1484. fprintf(pp, " 0=%d", op_type);
  1485. }
  1486. else if (n.op == "Crop")
  1487. {
  1488. int num_args = n.attr("num_args");
  1489. std::vector<int> offset = n.attr("offset");
  1490. int woffset = 0;
  1491. int hoffset = 0;
  1492. if (offset.size() == 2)
  1493. {
  1494. woffset = offset[1];
  1495. hoffset = offset[0];
  1496. }
  1497. fprintf(pp, " 0=%d", woffset);
  1498. fprintf(pp, " 1=%d", hoffset);
  1499. fprintf(pp, " 2=0");
  1500. if (num_args == 1)
  1501. {
  1502. std::vector<int> h_w = n.attr("h_w");
  1503. fprintf(pp, " 3=%d", h_w[1]);
  1504. fprintf(pp, " 4=%d", h_w[0]);
  1505. fprintf(pp, " 5=0");
  1506. }
  1507. }
  1508. else if (n.op == "Dropout")
  1509. {
  1510. // float p = n.attr("p");
  1511. // fprintf(pp, " 0=%d", p);
  1512. }
  1513. else if (n.op == "elemwise_add")
  1514. {
  1515. int op_type = 0;
  1516. fprintf(pp, " 0=%d", op_type);
  1517. }
  1518. else if (n.op == "elemwise_div")
  1519. {
  1520. int op_type = 3;
  1521. fprintf(pp, " 0=%d", op_type);
  1522. }
  1523. else if (n.op == "elemwise_mul")
  1524. {
  1525. int op_type = 2;
  1526. fprintf(pp, " 0=%d", op_type);
  1527. }
  1528. else if (n.op == "elemwise_sub")
  1529. {
  1530. int op_type = 1;
  1531. fprintf(pp, " 0=%d", op_type);
  1532. }
  1533. else if (n.op == "Embedding")
  1534. {
  1535. int input_dim = n.attr("input_dim");
  1536. int output_dim = n.attr("output_dim");
  1537. std::vector<float> weight_data = n.weight(0);
  1538. fprintf(pp, " 0=%d", output_dim);
  1539. fprintf(pp, " 1=%d", input_dim);
  1540. fprintf(pp, " 3=%d", (int)weight_data.size());
  1541. int quantize_tag = 0;
  1542. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1543. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1544. }
  1545. else if (n.op == "exp")
  1546. {
  1547. int op_type = 7;
  1548. fprintf(pp, " 0=%d", op_type);
  1549. }
  1550. else if (n.op == "expand_dims")
  1551. {
  1552. int axis = n.attr("axis");
  1553. int expand_w = 0;
  1554. int expand_h = 0;
  1555. int expand_c = 0;
  1556. if (axis == 0)
  1557. expand_c = 1;
  1558. if (axis == 1)
  1559. expand_h = 1;
  1560. if (axis == 2)
  1561. expand_w = 1;
  1562. fprintf(pp, " 0=%d", expand_w);
  1563. fprintf(pp, " 1=%d", expand_h);
  1564. fprintf(pp, " 2=%d", expand_c);
  1565. }
  1566. else if (n.op == "Flatten")
  1567. {
  1568. }
  1569. else if (n.op == "floor")
  1570. {
  1571. int op_type = 2;
  1572. fprintf(pp, " 0=%d", op_type);
  1573. }
  1574. else if (n.op == "FullyConnected")
  1575. {
  1576. int num_hidden = n.attr("num_hidden");
  1577. int no_bias = n.attr("no_bias");
  1578. // int flatten = n.attr("flatten");
  1579. // TODO flatten
  1580. std::vector<float> weight_data = n.weight(0);
  1581. std::vector<float> bias_data = n.weight(1);
  1582. fprintf(pp, " 0=%d", num_hidden);
  1583. fprintf(pp, " 1=%d", no_bias == 1 ? 0 : 1);
  1584. fprintf(pp, " 2=%d", (int)weight_data.size());
  1585. int quantize_tag = 0;
  1586. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1587. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1588. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1589. }
  1590. else if (n.op == "InstanceNorm")
  1591. {
  1592. float eps = n.has_attr("eps") ? n.attr("eps") : 0.001f;
  1593. std::vector<float> gamma_data = n.weight(0);
  1594. std::vector<float> beta_data = n.weight(1);
  1595. fprintf(pp, " 0=%d", (int)gamma_data.size());
  1596. fprintf(pp, " 1=%f", eps);
  1597. fwrite(gamma_data.data(), sizeof(float), gamma_data.size(), bp);
  1598. fwrite(beta_data.data(), sizeof(float), beta_data.size(), bp);
  1599. }
  1600. else if (n.op == "L2Normalization")
  1601. {
  1602. std::string mode = n.attr("mode");
  1603. float eps = n.has_attr("eps") ? n.attr("eps") : 1e-10;
  1604. int across_spatial = 0;
  1605. int across_channel = 1;
  1606. int channel_shared = 1;
  1607. int scale_data_size = 1;
  1608. if (mode == "instance")
  1609. {
  1610. across_spatial = 1;
  1611. across_channel = 1;
  1612. }
  1613. else if (mode == "channel")
  1614. {
  1615. across_spatial = 0;
  1616. across_channel = 1;
  1617. }
  1618. else if (mode == "spatial")
  1619. {
  1620. across_spatial = 1;
  1621. across_channel = 0;
  1622. }
  1623. fprintf(pp, " 0=%d", across_spatial);
  1624. fprintf(pp, " 4=%d", across_channel);
  1625. fprintf(pp, " 1=%d", channel_shared);
  1626. fprintf(pp, " 2=%f", eps);
  1627. fprintf(pp, " 3=%d", scale_data_size);
  1628. const float scale_data[1] = { 1.f };
  1629. fwrite(scale_data, sizeof(float), 1, bp);
  1630. }
  1631. else if (n.op == "LeakyReLU")
  1632. {
  1633. std::string type = n.attr("act_type");
  1634. if (type == "elu")
  1635. {
  1636. float slope = n.has_attr("slope") ? n.attr("slope") : 0.25f;
  1637. fprintf(pp, " 0=%f", slope);
  1638. }
  1639. else if (type == "leaky" || type.empty())
  1640. {
  1641. float slope = n.has_attr("slope") ? n.attr("slope") : 0.25f;
  1642. fprintf(pp, " 0=%f", slope);
  1643. }
  1644. else if (type == "prelu")
  1645. {
  1646. std::vector<float> weight_data = n.weight(0);
  1647. fprintf(pp, " 0=%d", (int)weight_data.size());
  1648. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1649. }
  1650. }
  1651. else if (n.op == "log")
  1652. {
  1653. int op_type = 8;
  1654. fprintf(pp, " 0=%d", op_type);
  1655. }
  1656. else if (n.op == "LogisticRegressionOutput")
  1657. {
  1658. }
  1659. else if (n.op == "max")
  1660. {
  1661. int operation = 4;
  1662. fprintf(pp, " 0=%d", operation);
  1663. }
  1664. else if (n.op == "maximum")
  1665. {
  1666. int op_type = 4;
  1667. fprintf(pp, " 0=%d", op_type);
  1668. }
  1669. else if (n.op == "mean")
  1670. {
  1671. int operation = 3;
  1672. fprintf(pp, " 0=%d", operation);
  1673. }
  1674. else if (n.op == "min")
  1675. {
  1676. int operation = 5;
  1677. fprintf(pp, " 0=%d", operation);
  1678. }
  1679. else if (n.op == "minimum")
  1680. {
  1681. int op_type = 5;
  1682. fprintf(pp, " 0=%d", op_type);
  1683. }
  1684. else if (n.op == "negative")
  1685. {
  1686. int op_type = 1;
  1687. fprintf(pp, " 0=%d", op_type);
  1688. }
  1689. else if (n.op == "Pad")
  1690. {
  1691. std::string mode = n.attr("mode");
  1692. std::vector<int> pad_width = n.attr("pad_width");
  1693. float constant_value = n.attr("constant_value");
  1694. int type = 0;
  1695. if (mode == "constant")
  1696. {
  1697. type = 0;
  1698. }
  1699. else if (mode == "edge")
  1700. {
  1701. type = 1;
  1702. }
  1703. else if (mode == "reflect")
  1704. {
  1705. // FIXME
  1706. }
  1707. if (pad_width.size() != 8)
  1708. {
  1709. fprintf(stderr, "Unsupported pad_width !\n");
  1710. }
  1711. int channel_before = pad_width[2];
  1712. int channel_after = pad_width[3];
  1713. if (channel_before != 0 || channel_after != 0)
  1714. {
  1715. // FIXME
  1716. fprintf(stderr, "Unsupported pad_width on channel axis !\n");
  1717. }
  1718. int top = pad_width[4];
  1719. int bottom = pad_width[5];
  1720. int left = pad_width[6];
  1721. int right = pad_width[7];
  1722. fprintf(pp, " 0=%d", top);
  1723. fprintf(pp, " 1=%d", bottom);
  1724. fprintf(pp, " 2=%d", left);
  1725. fprintf(pp, " 3=%d", right);
  1726. fprintf(pp, " 4=%d", type);
  1727. fprintf(pp, " 5=%f", constant_value);
  1728. }
  1729. else if (n.op == "Pooling")
  1730. {
  1731. std::string pool_type = n.attr("pool_type");
  1732. std::vector<int> kernel = n.attr("kernel");
  1733. std::vector<int> stride = n.attr("stride");
  1734. std::vector<int> pad = n.attr("pad");
  1735. std::string pooling_convention = n.attr("pooling_convention");
  1736. int global_pool = n.attr("global_pool");
  1737. int pool = 0;
  1738. if (pool_type == "max")
  1739. {
  1740. pool = 0;
  1741. }
  1742. else if (pool_type == "avg")
  1743. {
  1744. pool = 1;
  1745. }
  1746. int pad_mode = 1;
  1747. if (pooling_convention == "valid")
  1748. {
  1749. pad_mode = 1;
  1750. }
  1751. else if (pooling_convention == "full")
  1752. {
  1753. pad_mode = 0;
  1754. }
  1755. fprintf(pp, " 0=%d", pool);
  1756. if (!kernel.empty())
  1757. fprintf(pp, " 1=%d", kernel[0]);
  1758. if (!stride.empty())
  1759. fprintf(pp, " 2=%d", stride[0]);
  1760. if (!pad.empty())
  1761. fprintf(pp, " 3=%d", pad[0]);
  1762. fprintf(pp, " 4=%d", global_pool);
  1763. fprintf(pp, " 5=%d", pad_mode);
  1764. }
  1765. else if (n.op == "prod")
  1766. {
  1767. int operation = 6;
  1768. fprintf(pp, " 0=%d", operation);
  1769. }
  1770. else if (n.op == "reciprocal")
  1771. {
  1772. int op_type = 15;
  1773. fprintf(pp, " 0=%d", op_type);
  1774. }
  1775. else if (n.op == "relu")
  1776. {
  1777. }
  1778. else if (n.op == "Reshape")
  1779. {
  1780. std::vector<int> shape = n.attr("shape");
  1781. if (shape.size() == 1) {
  1782. fprintf(pp, " 0=%d", shape[0]);// should never reach here
  1783. } else if (shape.size() == 2) {
  1784. fprintf(pp, " 0=%d", shape[1]);
  1785. } else if (shape.size() == 3) {
  1786. fprintf(pp, " 0=%d", shape[2]);
  1787. fprintf(pp, " 1=%d", shape[1]);
  1788. } else if (shape.size() == 4) {
  1789. fprintf(pp, " 0=%d", shape[3]);
  1790. fprintf(pp, " 1=%d", shape[2]);
  1791. fprintf(pp, " 2=%d", shape[1]);
  1792. } else if (shape.size() == 5) {
  1793. fprintf(pp, " 0=%d", shape[4] * shape[3]);
  1794. fprintf(pp, " 1=%d", shape[2]);
  1795. fprintf(pp, " 2=%d", shape[1]);
  1796. }
  1797. }
  1798. else if (n.op == "ShuffleChannel")
  1799. {
  1800. int group = n.attr("group");
  1801. fprintf(pp, " 0=%d", group);
  1802. }
  1803. else if (n.op == "sigmoid")
  1804. {
  1805. }
  1806. else if (n.op == "sin")
  1807. {
  1808. int op_type = 9;
  1809. fprintf(pp, " 0=%d", op_type);
  1810. }
  1811. else if (n.op == "slice")
  1812. {
  1813. std::vector<int> begin = n.attr("begin");
  1814. std::vector<int> end = n.attr("end");
  1815. std::vector<int> step = n.attr("step");// TODO
  1816. // assert step == 1
  1817. for (int i=0; i<(int)step.size(); i++)
  1818. {
  1819. if (step[i] != 1)
  1820. fprintf(stderr, "Unsupported slice step !\n");
  1821. }
  1822. int woffset = 0;
  1823. int hoffset = 0;
  1824. int coffset = 0;
  1825. int outw = -233;
  1826. int outh = -233;
  1827. int outc = -233;
  1828. if (begin.size() == 2)
  1829. {
  1830. woffset = begin[1];
  1831. outw = end[1] == -1 ? -234 : end[1] - begin[1];
  1832. }
  1833. else if (begin.size() == 3)
  1834. {
  1835. woffset = begin[2];
  1836. hoffset = begin[1];
  1837. outw = end[2] == -1 ? -234 : end[2] - begin[2];
  1838. outh = end[1] == -1 ? -234 : end[1] - begin[1];
  1839. }
  1840. else if (begin.size() == 4)
  1841. {
  1842. woffset = begin[3];
  1843. hoffset = begin[2];
  1844. coffset = begin[1];
  1845. outw = end[3] == -1 ? -234 : end[3] - begin[3];
  1846. outh = end[2] == -1 ? -234 : end[2] - begin[2];
  1847. outc = end[1] == -1 ? -234 : end[1] - begin[1];
  1848. }
  1849. fprintf(pp, " 0=%d", woffset);
  1850. fprintf(pp, " 1=%d", hoffset);
  1851. fprintf(pp, " 2=%d", coffset);
  1852. fprintf(pp, " 3=%d", outw);
  1853. fprintf(pp, " 4=%d", outh);
  1854. fprintf(pp, " 5=%d", outc);
  1855. }
  1856. else if (n.op == "SliceChannel")
  1857. {
  1858. int num_outputs = n.attr("num_outputs");
  1859. int squeeze_axis = n.attr("squeeze_axis");// TODO
  1860. fprintf(pp, " -23300=%d", num_outputs);
  1861. for (int j=0; j<num_outputs; j++)
  1862. {
  1863. fprintf(pp, ",-233");
  1864. }
  1865. }
  1866. else if (n.op == "SoftmaxActivation")
  1867. {
  1868. fprintf(pp, " 1=1");
  1869. }
  1870. else if (n.op == "SoftmaxOutput")
  1871. {
  1872. fprintf(pp, " 1=1");
  1873. }
  1874. else if (n.op == "sqrt")
  1875. {
  1876. int op_type = 5;
  1877. fprintf(pp, " 0=%d", op_type);
  1878. }
  1879. else if (n.op == "square")
  1880. {
  1881. int op_type = 4;
  1882. fprintf(pp, " 0=%d", op_type);
  1883. }
  1884. else if (n.op == "sum")
  1885. {
  1886. int operation = 0;
  1887. fprintf(pp, " 0=%d", operation);
  1888. }
  1889. else if (n.op == "tan")
  1890. {
  1891. int op_type = 11;
  1892. fprintf(pp, " 0=%d", op_type);
  1893. }
  1894. else if (n.op == "tanh")
  1895. {
  1896. }
  1897. else if (n.op == "Transpose" || n.op == "transpose")
  1898. {
  1899. std::vector<int> axes = n.attr("axes");
  1900. if (axes.size() == 3) {
  1901. if (axes[1] == 2 && axes[2] == 1)
  1902. fprintf(pp, " 0=1");// h w c
  1903. else
  1904. fprintf(stderr, "Unsupported transpose type !\n");
  1905. }
  1906. else if (axes.size() == 4) {
  1907. if (axes[1] == 1 && axes[2] == 2 && axes[3] == 3)
  1908. fprintf(pp, " 0=0");// w h c
  1909. else if (axes[1] == 1 && axes[2] == 3 && axes[3] == 2)
  1910. fprintf(pp, " 0=1");// h w c
  1911. else if (axes[1] == 2 && axes[2] == 1 && axes[3] == 3)
  1912. fprintf(pp, " 0=2");// w c h
  1913. else if (axes[1] == 2 && axes[2] == 3 && axes[3] == 1)
  1914. fprintf(pp, " 0=3");// c w h
  1915. else if (axes[1] == 3 && axes[2] == 1 && axes[3] == 2)
  1916. fprintf(pp, " 0=4");// h c w
  1917. else if (axes[1] == 3 && axes[2] == 2 && axes[3] == 1)
  1918. fprintf(pp, " 0=5");// c h w
  1919. } else if (axes.size() == 5) {
  1920. if (axes[1] == 1 && axes[2] == 2 && axes[3] == 3 && axes[4] == 4)
  1921. fprintf(pp, " 0=0");// wx h c
  1922. else if (axes[1] == 1 && axes[2] == 3 && axes[3] == 4 && axes[4] == 2)
  1923. fprintf(pp, " 0=1");// h wx c
  1924. else if (axes[1] == 2 && axes[2] == 1 && axes[3] == 3 && axes[4] == 4)
  1925. fprintf(pp, " 0=2");// wx c h
  1926. else if (axes[1] == 2 && axes[2] == 3 && axes[3] == 4 && axes[4] == 1)
  1927. fprintf(pp, " 0=3");// c wx h
  1928. else if (axes[1] == 3 && axes[2] == 4 && axes[3] == 1 && axes[4] == 2)
  1929. fprintf(pp, " 0=4");// h c wx
  1930. else if (axes[1] == 3 && axes[2] == 4 && axes[3] == 2 && axes[4] == 1)
  1931. fprintf(pp, " 0=5");// c h wx
  1932. else
  1933. fprintf(stderr, "Unsupported transpose type !\n");
  1934. }
  1935. else
  1936. {
  1937. fprintf(stderr, "Unsupported transpose type !\n");
  1938. }
  1939. }
  1940. else if (n.op == "UpSampling")
  1941. {
  1942. int scale = n.attr("scale");
  1943. std::string sample_type = n.attr("sample_type");
  1944. if (sample_type == "nearest")
  1945. {
  1946. fprintf(pp, " 0=1");
  1947. fprintf(pp, " 1=%f", (float)scale);
  1948. fprintf(pp, " 2=%f", (float)scale);
  1949. }
  1950. else if (sample_type == "bilinear")
  1951. {
  1952. // DeconvolutionDepthWise
  1953. int num_filter = n.attr("num_filter");
  1954. std::vector<float> weight_data = n.weight(0);
  1955. int kernel = scale * 2 - scale % 2;
  1956. int stride = scale;
  1957. int pad = (scale - 1) / 2;
  1958. fprintf(pp, " 0=%d", num_filter);
  1959. fprintf(pp, " 1=%d", kernel);
  1960. fprintf(pp, " 2=1");
  1961. fprintf(pp, " 3=%d", stride);
  1962. fprintf(pp, " 4=%d", pad);
  1963. fprintf(pp, " 5=0");
  1964. fprintf(pp, " 6=%d", (int)weight_data.size());
  1965. fprintf(pp, " 7=%d", num_filter);
  1966. int quantize_tag = 0;
  1967. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1968. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1969. }
  1970. }
  1971. else
  1972. {
  1973. // TODO op specific params
  1974. std::map<std::string, std::string>::const_iterator it = n.attrs.begin();
  1975. for (; it != n.attrs.end(); it++)
  1976. {
  1977. fprintf(stderr, "# %s=%s\n", it->first.c_str(), it->second.c_str());
  1978. // fprintf(pp, " %s=%s", it->first.c_str(), it->second.c_str());
  1979. }
  1980. }
  1981. fprintf(pp, "\n");
  1982. for (int j=0; j<n.output_size; j++)
  1983. {
  1984. int input_uid = i | (j << 16);
  1985. if (node_reference.find(input_uid) != node_reference.end())
  1986. {
  1987. int refcount = node_reference[input_uid];
  1988. if (refcount > 1)
  1989. {
  1990. std::string output_name = n.name;
  1991. char splitname[256];
  1992. sprintf(splitname, "splitncnn_%d", internal_split);
  1993. fprintf(pp, "%-16s %-32s %d %d", "Split", splitname, 1, refcount);
  1994. if (j == 0)
  1995. {
  1996. fprintf(pp, " %s", output_name.c_str());
  1997. }
  1998. else
  1999. {
  2000. fprintf(pp, " %s_subncnn_%d", output_name.c_str(), j);
  2001. }
  2002. for (int k=0; k<refcount; k++)
  2003. {
  2004. if (j == 0)
  2005. {
  2006. fprintf(pp, " %s_splitncnn_%d", output_name.c_str(), k);
  2007. }
  2008. else
  2009. {
  2010. fprintf(pp, " %s_subncnn_%d_splitncnn_%d", output_name.c_str(), j, k);
  2011. }
  2012. }
  2013. fprintf(pp, "\n");
  2014. internal_split++;
  2015. }
  2016. }
  2017. }
  2018. }
  2019. fclose(pp);
  2020. fclose(bp);
  2021. return 0;
  2022. }