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 68 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292
  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" || n.op == "_add" || n.op == "_plus" || n.op == "_Plus")
  876. {
  877. fprintf(pp, "%-16s", "BinaryOp");
  878. }
  879. else if (n.op == "elemwise_div" || n.op == "_div" || n.op == "_Div")
  880. {
  881. fprintf(pp, "%-16s", "BinaryOp");
  882. }
  883. else if (n.op == "elemwise_mul" || n.op == "_mul" || n.op == "_Mul")
  884. {
  885. fprintf(pp, "%-16s", "BinaryOp");
  886. }
  887. else if (n.op == "elemwise_sub" || n.op == "_sub" || n.op == "_minus" || n.op == "_Minus")
  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 == "softmax")
  1024. {
  1025. fprintf(pp, "%-16s", "Softmax");
  1026. }
  1027. else if (n.op == "sqrt")
  1028. {
  1029. fprintf(pp, "%-16s", "UnaryOp");
  1030. }
  1031. else if (n.op == "square")
  1032. {
  1033. fprintf(pp, "%-16s", "UnaryOp");
  1034. }
  1035. else if (n.op == "sum")
  1036. {
  1037. fprintf(pp, "%-16s", "Reduction");
  1038. }
  1039. else if (n.op == "tan")
  1040. {
  1041. fprintf(pp, "%-16s", "UnaryOp");
  1042. }
  1043. else if (n.op == "tanh")
  1044. {
  1045. fprintf(pp, "%-16s", "TanH");
  1046. }
  1047. else if (n.op == "Transpose" || n.op == "transpose")
  1048. {
  1049. fprintf(pp, "%-16s", "Permute");
  1050. }
  1051. else if (n.op == "UpSampling")
  1052. {
  1053. std::string sample_type = n.attr("sample_type");
  1054. if (sample_type == "nearest")
  1055. {
  1056. fprintf(pp, "%-16s", "Interp");
  1057. }
  1058. else if (sample_type == "bilinear")
  1059. {
  1060. fprintf(pp, "%-16s", "DeconvolutionDepthWise");
  1061. }
  1062. }
  1063. else
  1064. {
  1065. fprintf(stderr, "%s not supported yet!\n", n.op.c_str());
  1066. fprintf(pp, "%-16s", n.op.c_str());
  1067. }
  1068. int input_size = n.inputs.size();
  1069. for (int j=0; j<(int)n.inputs.size(); j++)
  1070. {
  1071. int input_index = n.inputs[j];
  1072. if (nodes[input_index].is_weight())
  1073. {
  1074. input_size--;
  1075. }
  1076. }
  1077. if (n.op == "SoftmaxOutput" || n.op == "LogisticRegressionOutput")
  1078. {
  1079. // drop label
  1080. input_size--;
  1081. }
  1082. fprintf(pp, " %-32s %d %d", n.name.c_str(), input_size, n.output_size);
  1083. for (int j=0; j<(int)n.inputs.size(); j++)
  1084. {
  1085. int input_index = n.inputs[j];
  1086. int subinput_index = n.subinputs[j];
  1087. if (nodes[input_index].is_weight())
  1088. {
  1089. continue;
  1090. }
  1091. if (n.op == "SoftmaxOutput" || n.op == "LogisticRegressionOutput")
  1092. {
  1093. // drop label
  1094. if (j == 1)
  1095. continue;
  1096. }
  1097. std::string input_name = nodes[input_index].name;
  1098. if (subinput_index != 0)
  1099. {
  1100. char subinputsuffix[256];
  1101. sprintf(subinputsuffix, "_subncnn_%d", subinput_index);
  1102. input_name = input_name + subinputsuffix;
  1103. }
  1104. int input_uid = input_index | (subinput_index << 16);
  1105. if (node_reference.find(input_uid) != node_reference.end())
  1106. {
  1107. int refidx = node_reference[input_uid] - 1;
  1108. node_reference[input_uid] = refidx;
  1109. char splitsuffix[256];
  1110. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  1111. input_name = input_name + splitsuffix;
  1112. }
  1113. fprintf(pp, " %s", input_name.c_str());
  1114. }
  1115. fprintf(pp, " %s", n.name.c_str());
  1116. for (int j=1; j<n.output_size; j++)
  1117. {
  1118. fprintf(pp, " %s_subncnn_%d", n.name.c_str(), j);
  1119. }
  1120. if (n.op == "null")
  1121. {
  1122. // dummy input shape
  1123. // fprintf(pp, " 0 0 0");
  1124. }
  1125. else if (n.op == "_contrib_MultiBoxDetection")
  1126. {
  1127. float threshold = n.has_attr("threshold") ? n.attr("threshold") : 0.01f;
  1128. float nms_threshold = n.has_attr("nms_threshold") ? n.attr("nms_threshold") : 0.5f;
  1129. int nms_topk = n.has_attr("nms_topk") ? n.attr("nms_topk") : 300;
  1130. fprintf(pp, " 0=-233");
  1131. fprintf(pp, " 1=%f", nms_threshold);
  1132. fprintf(pp, " 2=%d", nms_topk);
  1133. int keep_top_k = 100;
  1134. fprintf(pp, " 3=%d", keep_top_k);
  1135. fprintf(pp, " 4=%f", threshold);
  1136. std::vector<float> variances = n.attr("variances");
  1137. if (variances.empty())
  1138. {
  1139. fprintf(pp, " 5=0.1");
  1140. fprintf(pp, " 6=0.1");
  1141. fprintf(pp, " 7=0.2");
  1142. fprintf(pp, " 8=0.2");
  1143. }
  1144. else
  1145. {
  1146. fprintf(pp, " 5=%f", variances[0]);
  1147. fprintf(pp, " 6=%f", variances[1]);
  1148. fprintf(pp, " 7=%f", variances[2]);
  1149. fprintf(pp, " 8=%f", variances[3]);
  1150. }
  1151. }
  1152. else if (n.op == "_contrib_MultiBoxPrior")
  1153. {
  1154. // mxnet-ssd encode size as scale factor, fill min_size
  1155. std::vector<float> sizes = n.attr("sizes");
  1156. fprintf(pp, " -23300=%d", (int)sizes.size());
  1157. for (int j=0; j<(int)sizes.size(); j++)
  1158. {
  1159. fprintf(pp, ",%f", sizes[j]);
  1160. }
  1161. std::vector<float> aspect_ratios = n.attr("ratios");
  1162. fprintf(pp, " -23302=%d", (int)aspect_ratios.size());
  1163. for (int j=0; j<(int)aspect_ratios.size(); j++)
  1164. {
  1165. fprintf(pp, ",%f", aspect_ratios[j]);
  1166. }
  1167. int flip = 0;
  1168. fprintf(pp, " 7=%d", flip);
  1169. int clip = n.attr("clip");
  1170. fprintf(pp, " 8=%d", clip);
  1171. // auto image size
  1172. fprintf(pp, " 9=-233");
  1173. fprintf(pp, " 10=-233");
  1174. std::vector<float> steps = n.attr("steps");
  1175. if (steps.empty() || (steps[0] == -1.f && steps[1] == -1.f))
  1176. {
  1177. // auto step
  1178. fprintf(pp, " 11=-233.0");
  1179. fprintf(pp, " 12=-233.0");
  1180. }
  1181. else
  1182. {
  1183. fprintf(pp, " 11=%f", steps[1]);
  1184. fprintf(pp, " 12=%f", steps[0]);
  1185. }
  1186. std::vector<float> offsets = n.attr("offsets");
  1187. if (offsets.empty() || (offsets[0] == 0.5f && offsets[1] == 0.5f))
  1188. {
  1189. fprintf(pp, " 13=0.5");
  1190. }
  1191. else
  1192. {
  1193. fprintf(stderr, "Unsupported offsets param! %f %f\n", offsets[0], offsets[1]);
  1194. }
  1195. }
  1196. else if (n.op == "_div_scalar")
  1197. {
  1198. int op_type = 3;
  1199. int with_scalar = 1;
  1200. float scalar = n.attr("scalar");
  1201. fprintf(pp, " 0=%d", op_type);
  1202. fprintf(pp, " 1=%d", with_scalar);
  1203. fprintf(pp, " 2=%f", scalar);
  1204. }
  1205. else if (n.op == "_maximum_scalar")
  1206. {
  1207. int op_type = 4;
  1208. int with_scalar = 1;
  1209. float scalar = n.attr("scalar");
  1210. fprintf(pp, " 0=%d", op_type);
  1211. fprintf(pp, " 1=%d", with_scalar);
  1212. fprintf(pp, " 2=%f", scalar);
  1213. }
  1214. else if (n.op == "_minimum_scalar")
  1215. {
  1216. int op_type = 5;
  1217. int with_scalar = 1;
  1218. float scalar = n.attr("scalar");
  1219. fprintf(pp, " 0=%d", op_type);
  1220. fprintf(pp, " 1=%d", with_scalar);
  1221. fprintf(pp, " 2=%f", scalar);
  1222. }
  1223. else if (n.op == "_minus_scalar")
  1224. {
  1225. int op_type = 1;
  1226. int with_scalar = 1;
  1227. float scalar = n.attr("scalar");
  1228. fprintf(pp, " 0=%d", op_type);
  1229. fprintf(pp, " 1=%d", with_scalar);
  1230. fprintf(pp, " 2=%f", scalar);
  1231. }
  1232. else if (n.op == "_mul_scalar")
  1233. {
  1234. int op_type = 2;
  1235. int with_scalar = 1;
  1236. float scalar = n.attr("scalar");
  1237. fprintf(pp, " 0=%d", op_type);
  1238. fprintf(pp, " 1=%d", with_scalar);
  1239. fprintf(pp, " 2=%f", scalar);
  1240. }
  1241. else if (n.op == "_plus_scalar")
  1242. {
  1243. int op_type = 0;
  1244. int with_scalar = 1;
  1245. float scalar = n.attr("scalar");
  1246. fprintf(pp, " 0=%d", op_type);
  1247. fprintf(pp, " 1=%d", with_scalar);
  1248. fprintf(pp, " 2=%f", scalar);
  1249. }
  1250. else if (n.op == "_power_scalar")
  1251. {
  1252. int op_type = 6;
  1253. int with_scalar = 1;
  1254. float scalar = n.attr("scalar");
  1255. fprintf(pp, " 0=%d", op_type);
  1256. fprintf(pp, " 1=%d", with_scalar);
  1257. fprintf(pp, " 2=%f", scalar);
  1258. }
  1259. else if (n.op == "_rdiv_scalar")
  1260. {
  1261. int op_type = 8;
  1262. int with_scalar = 1;
  1263. float scalar = n.attr("scalar");
  1264. fprintf(pp, " 0=%d", op_type);
  1265. fprintf(pp, " 1=%d", with_scalar);
  1266. fprintf(pp, " 2=%f", scalar);
  1267. }
  1268. else if (n.op == "_rminus_scalar")
  1269. {
  1270. int op_type = 7;
  1271. int with_scalar = 1;
  1272. float scalar = n.attr("scalar");
  1273. fprintf(pp, " 0=%d", op_type);
  1274. fprintf(pp, " 1=%d", with_scalar);
  1275. fprintf(pp, " 2=%f", scalar);
  1276. }
  1277. else if (n.op == "abs")
  1278. {
  1279. int op_type = 0;
  1280. fprintf(pp, " 0=%d", op_type);
  1281. }
  1282. else if (n.op == "Activation")
  1283. {
  1284. std::string type = n.attr("act_type");
  1285. if (type == "relu")
  1286. {
  1287. // fprintf(pp, " 0=%f", 0.f);
  1288. }
  1289. }
  1290. else if (n.op == "arccos")
  1291. {
  1292. int op_type = 13;
  1293. fprintf(pp, " 0=%d", op_type);
  1294. }
  1295. else if (n.op == "arcsin")
  1296. {
  1297. int op_type = 12;
  1298. fprintf(pp, " 0=%d", op_type);
  1299. }
  1300. else if (n.op == "arctan")
  1301. {
  1302. int op_type = 14;
  1303. fprintf(pp, " 0=%d", op_type);
  1304. }
  1305. else if (n.op == "BatchNorm")
  1306. {
  1307. float eps = 1e-3;
  1308. if (n.has_attr("eps")) {
  1309. eps = n.attr("eps");
  1310. }
  1311. std::vector<float> slope_data = n.weight(0);
  1312. std::vector<float> bias_data = n.weight(1);
  1313. int channels = slope_data.size();
  1314. std::vector<float> mean_data = n.weight(2, channels);
  1315. std::vector<float> var_data = n.weight(3, channels);
  1316. for (int j=0; j<(int)var_data.size(); j++)
  1317. {
  1318. var_data[j] += eps;
  1319. }
  1320. fprintf(pp, " 0=%d", channels);
  1321. int fix_gamma = n.has_attr("fix_gamma") ? n.attr("fix_gamma") : 0;
  1322. if (fix_gamma)
  1323. {
  1324. // slope data are all 0 here, force set 1
  1325. for (int j=0; j<channels; j++)
  1326. {
  1327. slope_data[j] = 1.f;
  1328. }
  1329. }
  1330. fwrite(slope_data.data(), sizeof(float), slope_data.size(), bp);
  1331. fwrite(mean_data.data(), sizeof(float), mean_data.size(), bp);
  1332. fwrite(var_data.data(), sizeof(float), var_data.size(), bp);
  1333. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1334. }
  1335. else if (n.op == "broadcast_add")
  1336. {
  1337. int op_type = 0;
  1338. fprintf(pp, " 0=%d", op_type);
  1339. }
  1340. else if (n.op == "broadcast_div")
  1341. {
  1342. int op_type = 3;
  1343. fprintf(pp, " 0=%d", op_type);
  1344. }
  1345. else if (n.op == "broadcast_mul")
  1346. {
  1347. int op_type = 2;
  1348. fprintf(pp, " 0=%d", op_type);
  1349. }
  1350. else if (n.op == "broadcast_sub")
  1351. {
  1352. int op_type = 1;
  1353. fprintf(pp, " 0=%d", op_type);
  1354. }
  1355. else if (n.op == "ceil")
  1356. {
  1357. int op_type = 3;
  1358. fprintf(pp, " 0=%d", op_type);
  1359. }
  1360. else if (n.op == "clip")
  1361. {
  1362. float min = n.attr("a_min");
  1363. float max = n.attr("a_max");
  1364. fprintf(pp, " 0=%f", min);
  1365. fprintf(pp, " 1=%f", max);
  1366. }
  1367. else if (n.op == "Concat")
  1368. {
  1369. int dim = n.has_attr("dim") ? n.attr("dim") : 1;
  1370. fprintf(pp, " 0=%d", dim-1);
  1371. }
  1372. else if (n.op == "Convolution")
  1373. {
  1374. int num_filter = n.attr("num_filter");
  1375. std::vector<int> kernel = n.attr("kernel");
  1376. std::vector<int> dilate = n.attr("dilate");
  1377. std::vector<int> stride = n.attr("stride");
  1378. std::vector<int> pad = n.attr("pad");
  1379. int no_bias = n.attr("no_bias");
  1380. int num_group = n.attr("num_group");
  1381. std::vector<float> weight_data = n.weight(0);
  1382. std::vector<float> bias_data = n.weight(1);
  1383. fprintf(pp, " 0=%d", num_filter);
  1384. if (kernel.size() == 1) {
  1385. fprintf(pp, " 1=%d", kernel[0]);
  1386. } else if (kernel.size() == 2) {
  1387. fprintf(pp, " 1=%d", kernel[1]);
  1388. fprintf(pp, " 11=%d", kernel[0]);
  1389. }
  1390. if (dilate.size() == 1) {
  1391. fprintf(pp, " 2=%d", dilate[0]);
  1392. } else if (dilate.size() == 2) {
  1393. fprintf(pp, " 2=%d", dilate[1]);
  1394. fprintf(pp, " 12=%d", dilate[0]);
  1395. }
  1396. if (stride.size() == 1) {
  1397. fprintf(pp, " 3=%d", stride[0]);
  1398. } else if (stride.size() == 2) {
  1399. fprintf(pp, " 3=%d", stride[1]);
  1400. fprintf(pp, " 13=%d", stride[0]);
  1401. }
  1402. if (pad.size() == 1) {
  1403. fprintf(pp, " 4=%d", pad[0]);
  1404. } else if (pad.size() == 2) {
  1405. fprintf(pp, " 4=%d", pad[1]);
  1406. fprintf(pp, " 14=%d", pad[0]);
  1407. }
  1408. fprintf(pp, " 5=%d", no_bias == 1 ? 0 : 1);
  1409. fprintf(pp, " 6=%d", (int)weight_data.size());
  1410. if (num_group > 1) {
  1411. fprintf(pp, " 7=%d", num_group);
  1412. }
  1413. int quantize_tag = 0;
  1414. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1415. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1416. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1417. }
  1418. else if (n.op == "Deconvolution")
  1419. {
  1420. int num_filter = n.attr("num_filter");
  1421. std::vector<int> kernel = n.attr("kernel");
  1422. std::vector<int> dilate = n.attr("dilate");
  1423. std::vector<int> stride = n.attr("stride");
  1424. std::vector<int> pad = n.attr("pad");
  1425. int no_bias = n.attr("no_bias");
  1426. int num_group = n.attr("num_group");
  1427. std::vector<float> weight_data = n.weight(0);
  1428. std::vector<float> bias_data = n.weight(1);
  1429. fprintf(pp, " 0=%d", num_filter);
  1430. if (kernel.size() == 1) {
  1431. fprintf(pp, " 1=%d", kernel[0]);
  1432. } else if (kernel.size() == 2) {
  1433. fprintf(pp, " 1=%d", kernel[1]);
  1434. fprintf(pp, " 11=%d", kernel[0]);
  1435. }
  1436. if (dilate.size() == 1) {
  1437. fprintf(pp, " 2=%d", dilate[0]);
  1438. } else if (dilate.size() == 2) {
  1439. fprintf(pp, " 2=%d", dilate[1]);
  1440. fprintf(pp, " 12=%d", dilate[0]);
  1441. }
  1442. if (stride.size() == 1) {
  1443. fprintf(pp, " 3=%d", stride[0]);
  1444. } else if (stride.size() == 2) {
  1445. fprintf(pp, " 3=%d", stride[1]);
  1446. fprintf(pp, " 13=%d", stride[0]);
  1447. }
  1448. if (pad.size() == 1) {
  1449. fprintf(pp, " 4=%d", pad[0]);
  1450. } else if (pad.size() == 2) {
  1451. fprintf(pp, " 4=%d", pad[1]);
  1452. fprintf(pp, " 14=%d", pad[0]);
  1453. }
  1454. fprintf(pp, " 5=%d", no_bias == 1 ? 0 : 1);
  1455. fprintf(pp, " 6=%d", (int)weight_data.size());
  1456. if (num_group > 1) {
  1457. fprintf(pp, " 7=%d", num_group);
  1458. }
  1459. int quantize_tag = 0;
  1460. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1461. int maxk = 0;
  1462. if (kernel.size() == 2)
  1463. {
  1464. maxk = kernel[1] * kernel[0];
  1465. }
  1466. else
  1467. {
  1468. maxk = kernel[0] * kernel[0];
  1469. }
  1470. for (int g=0; g<num_group; g++)
  1471. {
  1472. // reorder weight from inch-outch to outch-inch
  1473. int num_filter_g = num_filter / num_group;
  1474. int num_input = weight_data.size() / maxk / num_filter_g / num_group;
  1475. const float* weight_data_ptr = weight_data.data() + g * maxk * num_filter_g * num_input;
  1476. for (int k=0; k<num_filter_g; k++)
  1477. {
  1478. for (int j=0; j<num_input; j++)
  1479. {
  1480. fwrite(weight_data_ptr + (j*num_filter_g + k) * maxk, sizeof(float), maxk, bp);
  1481. }
  1482. }
  1483. }
  1484. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1485. }
  1486. else if (n.op == "cos")
  1487. {
  1488. int op_type = 10;
  1489. fprintf(pp, " 0=%d", op_type);
  1490. }
  1491. else if (n.op == "Crop")
  1492. {
  1493. int num_args = n.attr("num_args");
  1494. std::vector<int> offset = n.attr("offset");
  1495. int woffset = 0;
  1496. int hoffset = 0;
  1497. if (offset.size() == 2)
  1498. {
  1499. woffset = offset[1];
  1500. hoffset = offset[0];
  1501. }
  1502. fprintf(pp, " 0=%d", woffset);
  1503. fprintf(pp, " 1=%d", hoffset);
  1504. fprintf(pp, " 2=0");
  1505. if (num_args == 1)
  1506. {
  1507. std::vector<int> h_w = n.attr("h_w");
  1508. fprintf(pp, " 3=%d", h_w[1]);
  1509. fprintf(pp, " 4=%d", h_w[0]);
  1510. fprintf(pp, " 5=0");
  1511. }
  1512. }
  1513. else if (n.op == "Dropout")
  1514. {
  1515. // float p = n.attr("p");
  1516. // fprintf(pp, " 0=%d", p);
  1517. }
  1518. else if (n.op == "elemwise_add" || n.op == "_add" || n.op == "_plus" || n.op == "_Plus")
  1519. {
  1520. int op_type = 0;
  1521. fprintf(pp, " 0=%d", op_type);
  1522. }
  1523. else if (n.op == "elemwise_div" || n.op == "_div" || n.op == "_Div")
  1524. {
  1525. int op_type = 3;
  1526. fprintf(pp, " 0=%d", op_type);
  1527. }
  1528. else if (n.op == "elemwise_mul" || n.op == "_mul" || n.op == "_Mul")
  1529. {
  1530. int op_type = 2;
  1531. fprintf(pp, " 0=%d", op_type);
  1532. }
  1533. else if (n.op == "elemwise_sub" || n.op == "_sub" || n.op == "_minus" || n.op == "_Minus")
  1534. {
  1535. int op_type = 1;
  1536. fprintf(pp, " 0=%d", op_type);
  1537. }
  1538. else if (n.op == "Embedding")
  1539. {
  1540. int input_dim = n.attr("input_dim");
  1541. int output_dim = n.attr("output_dim");
  1542. std::vector<float> weight_data = n.weight(0);
  1543. fprintf(pp, " 0=%d", output_dim);
  1544. fprintf(pp, " 1=%d", input_dim);
  1545. fprintf(pp, " 3=%d", (int)weight_data.size());
  1546. int quantize_tag = 0;
  1547. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1548. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1549. }
  1550. else if (n.op == "exp")
  1551. {
  1552. int op_type = 7;
  1553. fprintf(pp, " 0=%d", op_type);
  1554. }
  1555. else if (n.op == "expand_dims")
  1556. {
  1557. int axis = n.attr("axis");
  1558. int expand_w = 0;
  1559. int expand_h = 0;
  1560. int expand_c = 0;
  1561. if (axis == 0)
  1562. expand_c = 1;
  1563. if (axis == 1)
  1564. expand_h = 1;
  1565. if (axis == 2)
  1566. expand_w = 1;
  1567. fprintf(pp, " 0=%d", expand_w);
  1568. fprintf(pp, " 1=%d", expand_h);
  1569. fprintf(pp, " 2=%d", expand_c);
  1570. }
  1571. else if (n.op == "Flatten")
  1572. {
  1573. }
  1574. else if (n.op == "floor")
  1575. {
  1576. int op_type = 2;
  1577. fprintf(pp, " 0=%d", op_type);
  1578. }
  1579. else if (n.op == "FullyConnected")
  1580. {
  1581. int num_hidden = n.attr("num_hidden");
  1582. int no_bias = n.attr("no_bias");
  1583. // int flatten = n.attr("flatten");
  1584. // TODO flatten
  1585. std::vector<float> weight_data = n.weight(0);
  1586. std::vector<float> bias_data = n.weight(1);
  1587. fprintf(pp, " 0=%d", num_hidden);
  1588. fprintf(pp, " 1=%d", no_bias == 1 ? 0 : 1);
  1589. fprintf(pp, " 2=%d", (int)weight_data.size());
  1590. int quantize_tag = 0;
  1591. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1592. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1593. fwrite(bias_data.data(), sizeof(float), bias_data.size(), bp);
  1594. }
  1595. else if (n.op == "InstanceNorm")
  1596. {
  1597. float eps = n.has_attr("eps") ? n.attr("eps") : 0.001f;
  1598. std::vector<float> gamma_data = n.weight(0);
  1599. std::vector<float> beta_data = n.weight(1);
  1600. fprintf(pp, " 0=%d", (int)gamma_data.size());
  1601. fprintf(pp, " 1=%f", eps);
  1602. fwrite(gamma_data.data(), sizeof(float), gamma_data.size(), bp);
  1603. fwrite(beta_data.data(), sizeof(float), beta_data.size(), bp);
  1604. }
  1605. else if (n.op == "L2Normalization")
  1606. {
  1607. std::string mode = n.attr("mode");
  1608. float eps = n.has_attr("eps") ? n.attr("eps") : 1e-10;
  1609. int across_spatial = 0;
  1610. int across_channel = 1;
  1611. int channel_shared = 1;
  1612. int scale_data_size = 1;
  1613. if (mode == "instance")
  1614. {
  1615. across_spatial = 1;
  1616. across_channel = 1;
  1617. }
  1618. else if (mode == "channel")
  1619. {
  1620. across_spatial = 0;
  1621. across_channel = 1;
  1622. }
  1623. else if (mode == "spatial")
  1624. {
  1625. across_spatial = 1;
  1626. across_channel = 0;
  1627. }
  1628. fprintf(pp, " 0=%d", across_spatial);
  1629. fprintf(pp, " 4=%d", across_channel);
  1630. fprintf(pp, " 1=%d", channel_shared);
  1631. fprintf(pp, " 2=%f", eps);
  1632. fprintf(pp, " 3=%d", scale_data_size);
  1633. const float scale_data[1] = { 1.f };
  1634. fwrite(scale_data, sizeof(float), 1, bp);
  1635. }
  1636. else if (n.op == "LeakyReLU")
  1637. {
  1638. std::string type = n.attr("act_type");
  1639. if (type == "elu")
  1640. {
  1641. float slope = n.has_attr("slope") ? n.attr("slope") : 0.25f;
  1642. fprintf(pp, " 0=%f", slope);
  1643. }
  1644. else if (type == "leaky" || type.empty())
  1645. {
  1646. float slope = n.has_attr("slope") ? n.attr("slope") : 0.25f;
  1647. fprintf(pp, " 0=%f", slope);
  1648. }
  1649. else if (type == "prelu")
  1650. {
  1651. std::vector<float> weight_data = n.weight(0);
  1652. fprintf(pp, " 0=%d", (int)weight_data.size());
  1653. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1654. }
  1655. }
  1656. else if (n.op == "log")
  1657. {
  1658. int op_type = 8;
  1659. fprintf(pp, " 0=%d", op_type);
  1660. }
  1661. else if (n.op == "LogisticRegressionOutput")
  1662. {
  1663. }
  1664. else if (n.op == "max")
  1665. {
  1666. int operation = 4;
  1667. fprintf(pp, " 0=%d", operation);
  1668. }
  1669. else if (n.op == "maximum")
  1670. {
  1671. int op_type = 4;
  1672. fprintf(pp, " 0=%d", op_type);
  1673. }
  1674. else if (n.op == "mean")
  1675. {
  1676. int operation = 3;
  1677. fprintf(pp, " 0=%d", operation);
  1678. }
  1679. else if (n.op == "min")
  1680. {
  1681. int operation = 5;
  1682. fprintf(pp, " 0=%d", operation);
  1683. }
  1684. else if (n.op == "minimum")
  1685. {
  1686. int op_type = 5;
  1687. fprintf(pp, " 0=%d", op_type);
  1688. }
  1689. else if (n.op == "negative")
  1690. {
  1691. int op_type = 1;
  1692. fprintf(pp, " 0=%d", op_type);
  1693. }
  1694. else if (n.op == "Pad")
  1695. {
  1696. std::string mode = n.attr("mode");
  1697. std::vector<int> pad_width = n.attr("pad_width");
  1698. float constant_value = n.attr("constant_value");
  1699. int type = 0;
  1700. if (mode == "constant")
  1701. {
  1702. type = 0;
  1703. }
  1704. else if (mode == "edge")
  1705. {
  1706. type = 1;
  1707. }
  1708. else if (mode == "reflect")
  1709. {
  1710. // FIXME
  1711. }
  1712. if (pad_width.size() != 8)
  1713. {
  1714. fprintf(stderr, "Unsupported pad_width !\n");
  1715. }
  1716. int channel_before = pad_width[2];
  1717. int channel_after = pad_width[3];
  1718. if (channel_before != 0 || channel_after != 0)
  1719. {
  1720. // FIXME
  1721. fprintf(stderr, "Unsupported pad_width on channel axis !\n");
  1722. }
  1723. int top = pad_width[4];
  1724. int bottom = pad_width[5];
  1725. int left = pad_width[6];
  1726. int right = pad_width[7];
  1727. fprintf(pp, " 0=%d", top);
  1728. fprintf(pp, " 1=%d", bottom);
  1729. fprintf(pp, " 2=%d", left);
  1730. fprintf(pp, " 3=%d", right);
  1731. fprintf(pp, " 4=%d", type);
  1732. fprintf(pp, " 5=%f", constant_value);
  1733. }
  1734. else if (n.op == "Pooling")
  1735. {
  1736. std::string pool_type = n.attr("pool_type");
  1737. std::vector<int> kernel = n.attr("kernel");
  1738. std::vector<int> stride = n.attr("stride");
  1739. std::vector<int> pad = n.attr("pad");
  1740. std::string pooling_convention = n.attr("pooling_convention");
  1741. int global_pool = n.attr("global_pool");
  1742. int pool = 0;
  1743. if (pool_type == "max")
  1744. {
  1745. pool = 0;
  1746. }
  1747. else if (pool_type == "avg")
  1748. {
  1749. pool = 1;
  1750. }
  1751. int pad_mode = 1;
  1752. if (pooling_convention == "valid")
  1753. {
  1754. pad_mode = 1;
  1755. }
  1756. else if (pooling_convention == "full")
  1757. {
  1758. pad_mode = 0;
  1759. }
  1760. fprintf(pp, " 0=%d", pool);
  1761. if (!kernel.empty())
  1762. fprintf(pp, " 1=%d", kernel[0]);
  1763. if (!stride.empty())
  1764. fprintf(pp, " 2=%d", stride[0]);
  1765. if (!pad.empty())
  1766. fprintf(pp, " 3=%d", pad[0]);
  1767. fprintf(pp, " 4=%d", global_pool);
  1768. fprintf(pp, " 5=%d", pad_mode);
  1769. }
  1770. else if (n.op == "prod")
  1771. {
  1772. int operation = 6;
  1773. fprintf(pp, " 0=%d", operation);
  1774. }
  1775. else if (n.op == "reciprocal")
  1776. {
  1777. int op_type = 15;
  1778. fprintf(pp, " 0=%d", op_type);
  1779. }
  1780. else if (n.op == "relu")
  1781. {
  1782. }
  1783. else if (n.op == "Reshape")
  1784. {
  1785. std::vector<int> shape = n.attr("shape");
  1786. if (shape.size() == 1) {
  1787. fprintf(pp, " 0=%d", shape[0]);// should never reach here
  1788. } else if (shape.size() == 2) {
  1789. fprintf(pp, " 0=%d", shape[1]);
  1790. } else if (shape.size() == 3) {
  1791. fprintf(pp, " 0=%d", shape[2]);
  1792. fprintf(pp, " 1=%d", shape[1]);
  1793. } else if (shape.size() == 4) {
  1794. fprintf(pp, " 0=%d", shape[3]);
  1795. fprintf(pp, " 1=%d", shape[2]);
  1796. fprintf(pp, " 2=%d", shape[1]);
  1797. } else if (shape.size() == 5) {
  1798. fprintf(pp, " 0=%d", shape[4] * shape[3]);
  1799. fprintf(pp, " 1=%d", shape[2]);
  1800. fprintf(pp, " 2=%d", shape[1]);
  1801. }
  1802. }
  1803. else if (n.op == "ShuffleChannel")
  1804. {
  1805. int group = n.attr("group");
  1806. fprintf(pp, " 0=%d", group);
  1807. }
  1808. else if (n.op == "sigmoid")
  1809. {
  1810. }
  1811. else if (n.op == "sin")
  1812. {
  1813. int op_type = 9;
  1814. fprintf(pp, " 0=%d", op_type);
  1815. }
  1816. else if (n.op == "slice")
  1817. {
  1818. std::vector<int> begin = n.attr("begin");
  1819. std::vector<int> end = n.attr("end");
  1820. std::vector<int> step = n.attr("step");// TODO
  1821. // assert step == 1
  1822. for (int i=0; i<(int)step.size(); i++)
  1823. {
  1824. if (step[i] != 1)
  1825. fprintf(stderr, "Unsupported slice step !\n");
  1826. }
  1827. int woffset = 0;
  1828. int hoffset = 0;
  1829. int coffset = 0;
  1830. int outw = -233;
  1831. int outh = -233;
  1832. int outc = -233;
  1833. if (begin.size() == 2)
  1834. {
  1835. woffset = begin[1];
  1836. outw = end[1] == -1 ? -234 : end[1] - begin[1];
  1837. }
  1838. else if (begin.size() == 3)
  1839. {
  1840. woffset = begin[2];
  1841. hoffset = begin[1];
  1842. outw = end[2] == -1 ? -234 : end[2] - begin[2];
  1843. outh = end[1] == -1 ? -234 : end[1] - begin[1];
  1844. }
  1845. else if (begin.size() == 4)
  1846. {
  1847. woffset = begin[3];
  1848. hoffset = begin[2];
  1849. coffset = begin[1];
  1850. outw = end[3] == -1 ? -234 : end[3] - begin[3];
  1851. outh = end[2] == -1 ? -234 : end[2] - begin[2];
  1852. outc = end[1] == -1 ? -234 : end[1] - begin[1];
  1853. }
  1854. fprintf(pp, " 0=%d", woffset);
  1855. fprintf(pp, " 1=%d", hoffset);
  1856. fprintf(pp, " 2=%d", coffset);
  1857. fprintf(pp, " 3=%d", outw);
  1858. fprintf(pp, " 4=%d", outh);
  1859. fprintf(pp, " 5=%d", outc);
  1860. }
  1861. else if (n.op == "SliceChannel")
  1862. {
  1863. int num_outputs = n.attr("num_outputs");
  1864. int squeeze_axis = n.attr("squeeze_axis");// TODO
  1865. fprintf(pp, " -23300=%d", num_outputs);
  1866. for (int j=0; j<num_outputs; j++)
  1867. {
  1868. fprintf(pp, ",-233");
  1869. }
  1870. }
  1871. else if (n.op == "SoftmaxActivation")
  1872. {
  1873. fprintf(pp, " 1=1");
  1874. }
  1875. else if (n.op == "SoftmaxOutput")
  1876. {
  1877. fprintf(pp, " 1=1");
  1878. }
  1879. else if (n.op == "softmax")
  1880. {
  1881. fprintf(pp, " 1=1");
  1882. }
  1883. else if (n.op == "sqrt")
  1884. {
  1885. int op_type = 5;
  1886. fprintf(pp, " 0=%d", op_type);
  1887. }
  1888. else if (n.op == "square")
  1889. {
  1890. int op_type = 4;
  1891. fprintf(pp, " 0=%d", op_type);
  1892. }
  1893. else if (n.op == "sum")
  1894. {
  1895. int operation = 0;
  1896. fprintf(pp, " 0=%d", operation);
  1897. }
  1898. else if (n.op == "tan")
  1899. {
  1900. int op_type = 11;
  1901. fprintf(pp, " 0=%d", op_type);
  1902. }
  1903. else if (n.op == "tanh")
  1904. {
  1905. }
  1906. else if (n.op == "Transpose" || n.op == "transpose")
  1907. {
  1908. std::vector<int> axes = n.attr("axes");
  1909. if (axes.size() == 3) {
  1910. if (axes[1] == 2 && axes[2] == 1)
  1911. fprintf(pp, " 0=1");// h w c
  1912. else
  1913. fprintf(stderr, "Unsupported transpose type !\n");
  1914. }
  1915. else if (axes.size() == 4) {
  1916. if (axes[1] == 1 && axes[2] == 2 && axes[3] == 3)
  1917. fprintf(pp, " 0=0");// w h c
  1918. else if (axes[1] == 1 && axes[2] == 3 && axes[3] == 2)
  1919. fprintf(pp, " 0=1");// h w c
  1920. else if (axes[1] == 2 && axes[2] == 1 && axes[3] == 3)
  1921. fprintf(pp, " 0=2");// w c h
  1922. else if (axes[1] == 2 && axes[2] == 3 && axes[3] == 1)
  1923. fprintf(pp, " 0=3");// c w h
  1924. else if (axes[1] == 3 && axes[2] == 1 && axes[3] == 2)
  1925. fprintf(pp, " 0=4");// h c w
  1926. else if (axes[1] == 3 && axes[2] == 2 && axes[3] == 1)
  1927. fprintf(pp, " 0=5");// c h w
  1928. } else if (axes.size() == 5) {
  1929. if (axes[1] == 1 && axes[2] == 2 && axes[3] == 3 && axes[4] == 4)
  1930. fprintf(pp, " 0=0");// wx h c
  1931. else if (axes[1] == 1 && axes[2] == 3 && axes[3] == 4 && axes[4] == 2)
  1932. fprintf(pp, " 0=1");// h wx c
  1933. else if (axes[1] == 2 && axes[2] == 1 && axes[3] == 3 && axes[4] == 4)
  1934. fprintf(pp, " 0=2");// wx c h
  1935. else if (axes[1] == 2 && axes[2] == 3 && axes[3] == 4 && axes[4] == 1)
  1936. fprintf(pp, " 0=3");// c wx h
  1937. else if (axes[1] == 3 && axes[2] == 4 && axes[3] == 1 && axes[4] == 2)
  1938. fprintf(pp, " 0=4");// h c wx
  1939. else if (axes[1] == 3 && axes[2] == 4 && axes[3] == 2 && axes[4] == 1)
  1940. fprintf(pp, " 0=5");// c h wx
  1941. else
  1942. fprintf(stderr, "Unsupported transpose type !\n");
  1943. }
  1944. else
  1945. {
  1946. fprintf(stderr, "Unsupported transpose type !\n");
  1947. }
  1948. }
  1949. else if (n.op == "UpSampling")
  1950. {
  1951. int scale = n.attr("scale");
  1952. std::string sample_type = n.attr("sample_type");
  1953. if (sample_type == "nearest")
  1954. {
  1955. fprintf(pp, " 0=1");
  1956. fprintf(pp, " 1=%f", (float)scale);
  1957. fprintf(pp, " 2=%f", (float)scale);
  1958. }
  1959. else if (sample_type == "bilinear")
  1960. {
  1961. // DeconvolutionDepthWise
  1962. int num_filter = n.attr("num_filter");
  1963. std::vector<float> weight_data = n.weight(0);
  1964. int kernel = scale * 2 - scale % 2;
  1965. int stride = scale;
  1966. int pad = (scale - 1) / 2;
  1967. fprintf(pp, " 0=%d", num_filter);
  1968. fprintf(pp, " 1=%d", kernel);
  1969. fprintf(pp, " 2=1");
  1970. fprintf(pp, " 3=%d", stride);
  1971. fprintf(pp, " 4=%d", pad);
  1972. fprintf(pp, " 5=0");
  1973. fprintf(pp, " 6=%d", (int)weight_data.size());
  1974. fprintf(pp, " 7=%d", num_filter);
  1975. int quantize_tag = 0;
  1976. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1977. fwrite(weight_data.data(), sizeof(float), weight_data.size(), bp);
  1978. }
  1979. }
  1980. else
  1981. {
  1982. // TODO op specific params
  1983. std::map<std::string, std::string>::const_iterator it = n.attrs.begin();
  1984. for (; it != n.attrs.end(); it++)
  1985. {
  1986. fprintf(stderr, "# %s=%s\n", it->first.c_str(), it->second.c_str());
  1987. // fprintf(pp, " %s=%s", it->first.c_str(), it->second.c_str());
  1988. }
  1989. }
  1990. fprintf(pp, "\n");
  1991. for (int j=0; j<n.output_size; j++)
  1992. {
  1993. int input_uid = i | (j << 16);
  1994. if (node_reference.find(input_uid) != node_reference.end())
  1995. {
  1996. int refcount = node_reference[input_uid];
  1997. if (refcount > 1)
  1998. {
  1999. std::string output_name = n.name;
  2000. char splitname[256];
  2001. sprintf(splitname, "splitncnn_%d", internal_split);
  2002. fprintf(pp, "%-16s %-32s %d %d", "Split", splitname, 1, refcount);
  2003. if (j == 0)
  2004. {
  2005. fprintf(pp, " %s", output_name.c_str());
  2006. }
  2007. else
  2008. {
  2009. fprintf(pp, " %s_subncnn_%d", output_name.c_str(), j);
  2010. }
  2011. for (int k=0; k<refcount; k++)
  2012. {
  2013. if (j == 0)
  2014. {
  2015. fprintf(pp, " %s_splitncnn_%d", output_name.c_str(), k);
  2016. }
  2017. else
  2018. {
  2019. fprintf(pp, " %s_subncnn_%d_splitncnn_%d", output_name.c_str(), j, k);
  2020. }
  2021. }
  2022. fprintf(pp, "\n");
  2023. internal_split++;
  2024. }
  2025. }
  2026. }
  2027. }
  2028. fclose(pp);
  2029. fclose(bp);
  2030. return 0;
  2031. }