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