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