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.

mlir2ncnn.cpp 58 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  1. // Copyright 2020 Tencent
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. #include <stdio.h>
  4. #include <map>
  5. #include <set>
  6. #include <mlir/Dialect/StandardOps/IR/Ops.h>
  7. #include <mlir/IR/PatternMatch.h>
  8. #include <mlir/Parser.h>
  9. #include <mlir/Pass/Pass.h>
  10. #include <mlir/Pass/PassManager.h>
  11. #include <mlir/Transforms/Passes.h>
  12. #include "tf_dialect.h"
  13. #include "ncnn_dialect.h"
  14. static std::string get_mlir_value_uniq_id(const mlir::Value& value)
  15. {
  16. if (value.getLoc().isa<mlir::FileLineColLoc>())
  17. {
  18. mlir::FileLineColLoc floc = value.getLoc().cast<mlir::FileLineColLoc>();
  19. return std::to_string(floc.getLine()) + ":" + std::to_string(floc.getColumn());
  20. }
  21. if (value.getLoc().isa<mlir::FusedLoc>())
  22. {
  23. mlir::FileLineColLoc floc = value.getLoc().cast<mlir::FusedLoc>().getLocations().front().cast<mlir::FileLineColLoc>();
  24. return std::to_string(floc.getLine()) + ":" + std::to_string(floc.getColumn());
  25. }
  26. fprintf(stderr, "unhandled get_mlir_value_uniq_id\n");
  27. return std::string();
  28. }
  29. static std::string get_attr_s(const mlir::Attribute& attr)
  30. {
  31. std::string s;
  32. if (attr.isa<mlir::StringAttr>())
  33. {
  34. mlir::StringAttr a = attr.cast<mlir::StringAttr>();
  35. s = a.getValue().str();
  36. }
  37. return s;
  38. }
  39. static int get_attr_b(const mlir::Attribute& attr)
  40. {
  41. int i;
  42. if (attr.isa<mlir::BoolAttr>())
  43. {
  44. mlir::BoolAttr a = attr.cast<mlir::BoolAttr>();
  45. i = a.getValue() ? 1 : 0;
  46. }
  47. else
  48. {
  49. fprintf(stderr, "not BoolAttr\n");
  50. }
  51. return i;
  52. }
  53. static int get_attr_i(const mlir::Attribute& attr)
  54. {
  55. int i;
  56. if (attr.isa<mlir::IntegerAttr>())
  57. {
  58. mlir::IntegerAttr a = attr.cast<mlir::IntegerAttr>();
  59. i = (int)a.getInt();
  60. }
  61. else
  62. {
  63. fprintf(stderr, "not IntegerAttr\n");
  64. }
  65. return i;
  66. }
  67. static float get_attr_f(const mlir::Attribute& attr)
  68. {
  69. float f;
  70. if (attr.isa<mlir::FloatAttr>())
  71. {
  72. mlir::FloatAttr a = attr.cast<mlir::FloatAttr>();
  73. f = (float)a.getValueAsDouble();
  74. }
  75. else
  76. {
  77. fprintf(stderr, "not FloatAttr\n");
  78. }
  79. return f;
  80. }
  81. static std::vector<int> get_attr_ai(const mlir::Attribute& attr)
  82. {
  83. std::vector<int> v;
  84. if (attr.isa<mlir::ArrayAttr>())
  85. {
  86. mlir::ArrayAttr a = attr.cast<mlir::ArrayAttr>();
  87. const int array_size = a.getValue().size();
  88. v.resize(array_size);
  89. for (int j = 0; j < array_size; j++)
  90. {
  91. if (a[j].isa<mlir::IntegerAttr>())
  92. {
  93. int64_t ii = a[j].cast<mlir::IntegerAttr>().getInt();
  94. v[j] = std::max(std::min(ii, (int64_t)INT_MAX), (int64_t)INT_MIN);
  95. }
  96. }
  97. }
  98. else if (attr.isa<mlir::DenseIntElementsAttr>())
  99. {
  100. mlir::DenseIntElementsAttr ai = attr.cast<mlir::DenseIntElementsAttr>();
  101. for (auto ii : ai.getIntValues())
  102. {
  103. v.push_back(ii.getSExtValue());
  104. }
  105. }
  106. else
  107. {
  108. fprintf(stderr, "not ArrayAttr or DenseIntElementsAttr\n");
  109. }
  110. return v;
  111. }
  112. static std::vector<float> get_attr_af(const mlir::Attribute& attr)
  113. {
  114. std::vector<float> v;
  115. if (attr.isa<mlir::ArrayAttr>())
  116. {
  117. mlir::ArrayAttr a = attr.cast<mlir::ArrayAttr>();
  118. const int array_size = a.getValue().size();
  119. v.resize(array_size);
  120. for (int j = 0; j < array_size; j++)
  121. {
  122. if (a[j].isa<mlir::FloatAttr>())
  123. {
  124. double ff = a[j].cast<mlir::FloatAttr>().getValueAsDouble();
  125. v[j] = ff;
  126. }
  127. }
  128. }
  129. else if (attr.isa<mlir::DenseFPElementsAttr>())
  130. {
  131. mlir::DenseFPElementsAttr af = attr.cast<mlir::DenseFPElementsAttr>();
  132. for (auto ff : af.getFloatValues())
  133. {
  134. v.push_back(ff.convertToFloat());
  135. }
  136. }
  137. else
  138. {
  139. fprintf(stderr, "not ArrayAttr or DenseFPElementsAttr\n");
  140. }
  141. return v;
  142. }
  143. static std::string get_operation_attr_s(const mlir::Operation& _operation, const char* key)
  144. {
  145. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  146. mlir::Attribute attr = operation.getAttr(key);
  147. return get_attr_s(attr);
  148. }
  149. static int get_operation_attr_b(const mlir::Operation& _operation, const char* key)
  150. {
  151. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  152. mlir::Attribute attr = operation.getAttr(key);
  153. return get_attr_b(attr);
  154. }
  155. static int get_operation_attr_i(const mlir::Operation& _operation, const char* key)
  156. {
  157. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  158. mlir::Attribute attr = operation.getAttr(key);
  159. return get_attr_i(attr);
  160. }
  161. static float get_operation_attr_f(const mlir::Operation& _operation, const char* key)
  162. {
  163. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  164. mlir::Attribute attr = operation.getAttr(key);
  165. return get_attr_f(attr);
  166. }
  167. static std::vector<int> get_operation_attr_ai(const mlir::Operation& _operation, const char* key)
  168. {
  169. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  170. mlir::Attribute attr = operation.getAttr(key);
  171. return get_attr_ai(attr);
  172. }
  173. static std::vector<float> get_operation_attr_af(const mlir::Operation& _operation, const char* key)
  174. {
  175. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  176. mlir::Attribute attr = operation.getAttr(key);
  177. return get_attr_af(attr);
  178. }
  179. int main(int argc, char** argv)
  180. {
  181. if (!(argc == 2 || argc == 4))
  182. {
  183. fprintf(stderr, "Usage: %s [mlir] [ncnnparam] [ncnnbin]\n", argv[0]);
  184. return -1;
  185. }
  186. const char* mlirpath = argv[1];
  187. const char* ncnn_prototxt = argc == 4 ? argv[2] : "ncnn.param";
  188. const char* ncnn_modelbin = argc == 4 ? argv[3] : "ncnn.bin";
  189. mlir::MLIRContext context;
  190. context.getOrLoadDialect<mlir::StandardOpsDialect>();
  191. context.getOrLoadDialect<mlir::TF::TensorFlowDialect>();
  192. context.getOrLoadDialect<mlir::ncnn::NCNNDialect>();
  193. mlir::OwningModuleRef m = mlir::parseSourceFile(mlirpath, &context);
  194. mlir::PassManager pm(&context);
  195. pm.addNestedPass<mlir::FuncOp>(mlir::ncnn::createNCNNOptimizePass());
  196. if (pm.run(*m).failed())
  197. {
  198. fprintf(stderr, "canonicalizer pass failed\n");
  199. return -1;
  200. }
  201. // m->dump();
  202. mlir::FuncOp main_fn = m->lookupSymbol<mlir::FuncOp>("main");
  203. auto& bb = main_fn.getBlocks().front();
  204. // bb.dump();
  205. FILE* pp = fopen(ncnn_prototxt, "wb");
  206. FILE* bp = fopen(ncnn_modelbin, "wb");
  207. // node reference
  208. std::map<std::string, int> node_reference;
  209. // weight node and weight reshape node
  210. std::map<std::string, mlir::Attribute> weights;
  211. fprintf(pp, "7767517\n");
  212. const mlir::Block::OpListType& operations = bb.getOperations();
  213. int node_count = operations.size();
  214. // global definition line
  215. // [layer count] [blob count]
  216. std::set<std::string> blob_names;
  217. for (const mlir::Operation& _operation : operations)
  218. {
  219. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  220. std::string op = operation.getName().getStringRef().str();
  221. int num_input = (int)operation.getNumOperands();
  222. int num_output = (int)operation.getNumResults();
  223. if (op == "tf.Const")
  224. {
  225. // weight
  226. std::string output_name = get_mlir_value_uniq_id(operation.getResult(0));
  227. weights[output_name] = operation.getAttr("value");
  228. }
  229. for (int j = 0; j < num_input; j++)
  230. {
  231. std::string input_name = get_mlir_value_uniq_id(operation.getOperand(j));
  232. blob_names.insert(input_name);
  233. if (node_reference.find(input_name) == node_reference.end())
  234. {
  235. node_reference[input_name] = 1;
  236. }
  237. else
  238. {
  239. node_reference[input_name] = node_reference[input_name] + 1;
  240. }
  241. }
  242. for (int j = 0; j < num_output; j++)
  243. {
  244. std::string output_name = get_mlir_value_uniq_id(operation.getResult(j));
  245. blob_names.insert(output_name);
  246. node_reference[output_name] = 0;
  247. }
  248. }
  249. // reduce common const weight node_reference
  250. for (const mlir::Operation& _operation : operations)
  251. {
  252. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  253. std::string op = operation.getName().getStringRef().str();
  254. if (op == "ncnn.KerasConv2D")
  255. {
  256. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  257. std::string bias_name = get_mlir_value_uniq_id(operation.getOperand(2));
  258. node_reference[weight_name] -= 1;
  259. node_reference[bias_name] -= 1;
  260. }
  261. else if (op == "ncnn.KerasDense")
  262. {
  263. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  264. std::string bias_name = get_mlir_value_uniq_id(operation.getOperand(2));
  265. node_reference[weight_name] -= 1;
  266. node_reference[bias_name] -= 1;
  267. }
  268. else if (op == "ncnn.KerasBatchNorm")
  269. {
  270. std::string gamma_name = get_mlir_value_uniq_id(operation.getOperand(1));
  271. std::string bias_name = get_mlir_value_uniq_id(operation.getOperand(2));
  272. node_reference[gamma_name] -= 1;
  273. node_reference[bias_name] -= 1;
  274. }
  275. else if (op == "ncnn.InstanceNormAffine")
  276. {
  277. std::string gamma_name = get_mlir_value_uniq_id(operation.getOperand(1));
  278. std::string bias_name = get_mlir_value_uniq_id(operation.getOperand(2));
  279. node_reference[gamma_name] -= 1;
  280. node_reference[bias_name] -= 1;
  281. }
  282. else if (op == "tf.ConcatV2")
  283. {
  284. std::string axis_name = get_mlir_value_uniq_id(operation.getOperand(operation.getNumOperands() - 1));
  285. node_reference[axis_name] -= 1;
  286. }
  287. else if (op == "tf.Conv2D")
  288. {
  289. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  290. node_reference[weight_name] -= 1;
  291. }
  292. else if (op == "tf.Conv2DBackpropInput")
  293. {
  294. std::string output_shape_name = get_mlir_value_uniq_id(operation.getOperand(0));
  295. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  296. node_reference[output_shape_name] -= 1;
  297. node_reference[weight_name] -= 1;
  298. }
  299. else if (op == "tf.DepthwiseConv2dNative")
  300. {
  301. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  302. node_reference[weight_name] -= 1;
  303. }
  304. else if (op == "tf.MatMul")
  305. {
  306. int transpose_a = get_operation_attr_b(operation, "transpose_a");
  307. int transpose_b = get_operation_attr_b(operation, "transpose_b");
  308. if (transpose_a == 0 && transpose_b == 1)
  309. {
  310. // InnerProduct-like A * B + C
  311. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  312. node_reference[weight_name] -= 1;
  313. }
  314. }
  315. else if (op == "tf.Mean")
  316. {
  317. std::string reduction_indices_name = get_mlir_value_uniq_id(operation.getOperand(1));
  318. node_reference[reduction_indices_name] -= 1;
  319. }
  320. else if (op == "tf.Pad")
  321. {
  322. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  323. node_reference[weight_name] -= 1;
  324. }
  325. else if (op == "tf.Reshape")
  326. {
  327. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  328. node_reference[weight_name] -= 1;
  329. }
  330. else if (op == "tf.ResizeBilinear")
  331. {
  332. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  333. node_reference[weight_name] -= 1;
  334. }
  335. else if (op == "tf.ResizeNearestNeighbor")
  336. {
  337. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  338. node_reference[weight_name] -= 1;
  339. }
  340. else if (op == "tf.StridedSlice")
  341. {
  342. std::string begin_name = get_mlir_value_uniq_id(operation.getOperand(1));
  343. std::string end_name = get_mlir_value_uniq_id(operation.getOperand(2));
  344. std::string strides_name = get_mlir_value_uniq_id(operation.getOperand(3));
  345. node_reference[begin_name] -= 1;
  346. node_reference[end_name] -= 1;
  347. node_reference[strides_name] -= 1;
  348. }
  349. }
  350. // count all weight node with zero reference
  351. int zero_reference_weight_node_count = 0;
  352. for (std::map<std::string, mlir::Attribute>::iterator it = weights.begin(); it != weights.end(); it++)
  353. {
  354. const std::string& input_name = it->first;
  355. int refcount = node_reference[input_name];
  356. if (refcount == 0)
  357. zero_reference_weight_node_count++;
  358. }
  359. // remove node_reference entry with reference equals to one
  360. int split_layer_count = 0;
  361. int splitncnn_blob_count = 0;
  362. // split node reference
  363. std::map<std::string, int> split_node_reference;
  364. for (std::map<std::string, int>::iterator it = node_reference.begin(); it != node_reference.end(); it++)
  365. {
  366. if (it->second > 1)
  367. {
  368. split_layer_count++;
  369. splitncnn_blob_count += it->second;
  370. split_node_reference[it->first] = it->second;
  371. }
  372. }
  373. fprintf(pp, "%lu %lu\n", node_count - zero_reference_weight_node_count + split_layer_count, blob_names.size() - zero_reference_weight_node_count + splitncnn_blob_count);
  374. int internal_split = 0;
  375. // place MemoryData next
  376. for (std::map<std::string, mlir::Attribute>::iterator weight_it = weights.begin(); weight_it != weights.end(); weight_it++)
  377. {
  378. const std::string& input_name = weight_it->first;
  379. int refcount = node_reference[input_name];
  380. if (refcount == 0)
  381. {
  382. continue;
  383. }
  384. fprintf(pp, "%-16s %-24s 0 1 %s", "MemoryData", input_name.c_str(), input_name.c_str());
  385. const mlir::Attribute& M = weights[input_name];
  386. llvm::ArrayRef<int64_t> shape = M.getType().cast<mlir::RankedTensorType>().getShape();
  387. // c wc hwc
  388. if (shape.size() == 0)
  389. {
  390. // scalar
  391. fprintf(pp, " 0=1");
  392. }
  393. else if (shape.size() == 1)
  394. {
  395. fprintf(pp, " 0=%d", (int)shape[0]);
  396. }
  397. else if (shape.size() == 2)
  398. {
  399. fprintf(pp, " 0=%d", (int)shape[1]);
  400. fprintf(pp, " 1=%d", (int)shape[0]);
  401. }
  402. else if (shape.size() == 3)
  403. {
  404. fprintf(pp, " 0=%d", (int)shape[1]);
  405. fprintf(pp, " 1=%d", (int)shape[0]);
  406. fprintf(pp, " 2=%d", (int)shape[2]);
  407. }
  408. fprintf(pp, "\n");
  409. std::vector<float> v = get_attr_af(M);
  410. if (shape.size() != 3)
  411. {
  412. fwrite(v.data(), sizeof(float), v.size(), bp);
  413. }
  414. else
  415. {
  416. int w = (int)shape[1];
  417. int h = (int)shape[0];
  418. int c = (int)shape[2];
  419. float tmp;
  420. // h-w-c to c-h-w
  421. for (int p = 0; p < c; p++)
  422. {
  423. for (int i = 0; i < h; i++)
  424. {
  425. for (int j = 0; j < w; j++)
  426. {
  427. tmp = v[i * w * c + j * c + p];
  428. fwrite(&tmp, sizeof(float), 1, bp);
  429. }
  430. }
  431. }
  432. }
  433. if (refcount <= 1)
  434. {
  435. continue;
  436. }
  437. char splitname[256];
  438. sprintf(splitname, "splitncnn_%d", internal_split);
  439. fprintf(pp, "%-16s %-24s %d %d", "Split", splitname, 1, refcount);
  440. fprintf(pp, " %s", input_name.c_str());
  441. for (int k = 0; k < refcount; k++)
  442. {
  443. fprintf(pp, " %s_splitncnn_%d", input_name.c_str(), k);
  444. }
  445. fprintf(pp, "\n");
  446. internal_split++;
  447. }
  448. // model op
  449. int g_opid = 0;
  450. for (const mlir::Operation& _operation : operations)
  451. {
  452. mlir::Operation& operation = const_cast<mlir::Operation&>(_operation);
  453. std::string op = operation.getName().getStringRef().str();
  454. int opid = g_opid++;
  455. int num_input = (int)operation.getNumOperands();
  456. int num_output = (int)operation.getNumResults();
  457. for (int i = 0; i < (int)operation.getNumOperands(); i++)
  458. {
  459. std::string input_name = get_mlir_value_uniq_id(operation.getOperand(i));
  460. // check weight
  461. if (weights.find(input_name) != weights.end() && node_reference[input_name] == 0)
  462. {
  463. num_input--;
  464. }
  465. }
  466. if (op == "std.return")
  467. {
  468. fprintf(pp, "%-16s", "Noop");
  469. }
  470. else if (op == "ncnn.BinaryOp")
  471. {
  472. fprintf(pp, "%-16s", "BinaryOp");
  473. }
  474. else if (op == "ncnn.KerasConv2D")
  475. {
  476. fprintf(pp, "%-16s", "Convolution");
  477. }
  478. else if (op == "ncnn.KerasDense")
  479. {
  480. fprintf(pp, "%-16s", "InnerProduct");
  481. }
  482. else if (op == "ncnn.KerasBatchNorm")
  483. {
  484. fprintf(pp, "%-16s", "BatchNorm");
  485. }
  486. else if (op == "ncnn.InstanceNorm")
  487. {
  488. fprintf(pp, "%-16s", "InstanceNorm");
  489. }
  490. else if (op == "ncnn.InstanceNormAffine")
  491. {
  492. fprintf(pp, "%-16s", "InstanceNorm");
  493. }
  494. else if (op == "ncnn.Swish")
  495. {
  496. fprintf(pp, "%-16s", "Swish");
  497. }
  498. else if (op == "tf.AddN")
  499. {
  500. fprintf(pp, "%-16s", "Eltwise");
  501. }
  502. else if (op == "tf.AddV2")
  503. {
  504. fprintf(pp, "%-16s", "BinaryOp");
  505. }
  506. else if (op == "tf.AvgPool")
  507. {
  508. fprintf(pp, "%-16s", "Pooling");
  509. }
  510. else if (op == "tf.BiasAdd")
  511. {
  512. fprintf(pp, "%-16s", "BinaryOp");
  513. }
  514. else if (op == "tf.ConcatV2")
  515. {
  516. fprintf(pp, "%-16s", "Concat");
  517. }
  518. else if (op == "tf.Const")
  519. {
  520. continue;
  521. }
  522. else if (op == "tf.Conv2D")
  523. {
  524. fprintf(pp, "%-16s", "Convolution");
  525. }
  526. else if (op == "tf.Conv2DBackpropInput")
  527. {
  528. fprintf(pp, "%-16s", "Deconvolution");
  529. }
  530. else if (op == "tf.DepthToSpace")
  531. {
  532. fprintf(pp, "%-16s", "PixelShuffle");
  533. }
  534. else if (op == "tf.DepthwiseConv2dNative")
  535. {
  536. fprintf(pp, "%-16s", "ConvolutionDepthWise");
  537. }
  538. else if (op == "tf.Identity")
  539. {
  540. fprintf(pp, "%-16s", "Noop");
  541. }
  542. else if (op == "tf.LeakyRelu")
  543. {
  544. fprintf(pp, "%-16s", "ReLU");
  545. }
  546. else if (op == "tf.MatMul")
  547. {
  548. int transpose_a = get_operation_attr_b(operation, "transpose_a");
  549. int transpose_b = get_operation_attr_b(operation, "transpose_b");
  550. if (transpose_a == 0 && transpose_b == 1)
  551. {
  552. // InnerProduct-like A * B + C
  553. fprintf(pp, "%-16s", "InnerProduct");
  554. }
  555. else
  556. {
  557. fprintf(pp, "%-16s", "Gemm");
  558. }
  559. }
  560. else if (op == "tf.Maximum")
  561. {
  562. fprintf(pp, "%-16s", "BinaryOp");
  563. }
  564. else if (op == "tf.MaxPool")
  565. {
  566. fprintf(pp, "%-16s", "Pooling");
  567. }
  568. else if (op == "tf.Mean")
  569. {
  570. std::string reduction_indices_name = get_mlir_value_uniq_id(operation.getOperand(1));
  571. const mlir::Attribute& R = weights[reduction_indices_name];
  572. std::vector<int> v = get_attr_ai(R);
  573. int keep_dims = get_operation_attr_b(operation, "keep_dims");
  574. if (keep_dims == 0 && v.size() == 2 && v[0] == 1 && v[1] == 2)
  575. {
  576. // global avg pooling style nhwc -> nc
  577. fprintf(pp, "%-16s", "Pooling");
  578. }
  579. else
  580. {
  581. fprintf(pp, "%-16s", "Reduction");
  582. }
  583. }
  584. else if (op == "tf.Minimum")
  585. {
  586. fprintf(pp, "%-16s", "BinaryOp");
  587. }
  588. else if (op == "tf.Mul")
  589. {
  590. fprintf(pp, "%-16s", "BinaryOp");
  591. }
  592. else if (op == "tf.Pad")
  593. {
  594. fprintf(pp, "%-16s", "Padding");
  595. }
  596. else if (op == "tf.Placeholder")
  597. {
  598. fprintf(pp, "%-16s", "Input");
  599. }
  600. else if (op == "tf.Relu")
  601. {
  602. fprintf(pp, "%-16s", "ReLU");
  603. }
  604. else if (op == "tf.Relu6")
  605. {
  606. fprintf(pp, "%-16s", "Clip");
  607. }
  608. else if (op == "tf.Reshape")
  609. {
  610. fprintf(pp, "%-16s", "Reshape");
  611. }
  612. else if (op == "tf.ResizeBilinear")
  613. {
  614. fprintf(pp, "%-16s", "Interp");
  615. }
  616. else if (op == "tf.ResizeNearestNeighbor")
  617. {
  618. fprintf(pp, "%-16s", "Interp");
  619. }
  620. else if (op == "tf.Sigmoid")
  621. {
  622. fprintf(pp, "%-16s", "Sigmoid");
  623. }
  624. else if (op == "tf.Softmax")
  625. {
  626. fprintf(pp, "%-16s", "Softmax");
  627. }
  628. else if (op == "tf.SpaceToDepth")
  629. {
  630. fprintf(pp, "%-16s", "Reorg");
  631. }
  632. else if (op == "tf.StridedSlice")
  633. {
  634. fprintf(pp, "%-16s", "Crop");
  635. }
  636. else if (op == "tf.Sub")
  637. {
  638. fprintf(pp, "%-16s", "BinaryOp");
  639. }
  640. else if (op == "tf.Tanh")
  641. {
  642. fprintf(pp, "%-16s", "TanH");
  643. }
  644. else
  645. {
  646. // TODO
  647. fprintf(stderr, "%s not supported yet!\n", op.c_str());
  648. fprintf(pp, "%-16s", op.c_str());
  649. }
  650. char opid_name[64];
  651. sprintf(opid_name, "op_%d", opid);
  652. fprintf(pp, " %-24s %d %d", opid_name, num_input, num_output);
  653. for (int i = 0; i < (int)operation.getNumOperands(); i++)
  654. {
  655. std::string input_name = get_mlir_value_uniq_id(operation.getOperand(i));
  656. // check weight
  657. if (weights.find(input_name) != weights.end() && node_reference[input_name] == 0)
  658. {
  659. continue;
  660. }
  661. if (split_node_reference.find(input_name) != split_node_reference.end())
  662. {
  663. int refidx = split_node_reference[input_name] - 1;
  664. split_node_reference[input_name] = refidx;
  665. char splitsuffix[256];
  666. sprintf(splitsuffix, "_splitncnn_%d", refidx);
  667. input_name = input_name + splitsuffix;
  668. }
  669. fprintf(pp, " %s", input_name.c_str());
  670. }
  671. for (int i = 0; i < num_output; i++)
  672. {
  673. std::string output_name = get_mlir_value_uniq_id(operation.getResult(i));
  674. fprintf(pp, " %s", output_name.c_str());
  675. }
  676. if (op == "std.return")
  677. {
  678. }
  679. else if (op == "ncnn.BinaryOp")
  680. {
  681. int op_type = get_operation_attr_i(operation, "op_type");
  682. int with_scalar = get_operation_attr_i(operation, "with_scalar");
  683. float b = get_operation_attr_f(operation, "b");
  684. fprintf(pp, " 0=%d", op_type);
  685. fprintf(pp, " 1=%d", with_scalar);
  686. fprintf(pp, " 2=%e", b);
  687. }
  688. else if (op == "ncnn.KerasConv2D")
  689. {
  690. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  691. std::string bias_name = get_mlir_value_uniq_id(operation.getOperand(2));
  692. const mlir::Attribute& W = weights[weight_name];
  693. const mlir::Attribute& B = weights[bias_name];
  694. llvm::ArrayRef<int64_t> shape = W.getType().cast<mlir::RankedTensorType>().getShape();
  695. // assert(shape.size() == 4)
  696. // kh-kw-inch-outch
  697. int kernel_size_h = shape[0];
  698. int kernel_size_w = shape[1];
  699. int num_input = shape[2];
  700. int num_output = shape[3];
  701. int weight_data_size = kernel_size_h * kernel_size_w * num_input * num_output;
  702. fprintf(pp, " 0=%d", num_output);
  703. fprintf(pp, " 1=%d", kernel_size_w);
  704. fprintf(pp, " 11=%d", kernel_size_h);
  705. fprintf(pp, " 6=%d", weight_data_size);
  706. std::vector<int> dilations = get_operation_attr_ai(operation, "dilations");
  707. std::vector<int> strides = get_operation_attr_ai(operation, "strides");
  708. std::string padding = get_operation_attr_s(operation, "padding");
  709. if (dilations.size() == 4)
  710. {
  711. fprintf(pp, " 2=%d", dilations[2]);
  712. fprintf(pp, " 12=%d", dilations[1]);
  713. }
  714. if (strides.size() == 4)
  715. {
  716. fprintf(pp, " 3=%d", strides[2]);
  717. fprintf(pp, " 13=%d", strides[1]);
  718. }
  719. if (padding == "EXPLICIT")
  720. {
  721. // nhwc = [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]
  722. std::vector<int> explicit_paddings = get_operation_attr_ai(operation, "explicit_paddings");
  723. fprintf(pp, " 4=%d", explicit_paddings[4]);
  724. fprintf(pp, " 15=%d", explicit_paddings[5]);
  725. fprintf(pp, " 14=%d", explicit_paddings[2]);
  726. fprintf(pp, " 16=%d", explicit_paddings[3]);
  727. }
  728. else if (padding == "VALID")
  729. {
  730. fprintf(pp, " 4=%d", 0);
  731. }
  732. else if (padding == "SAME")
  733. {
  734. fprintf(pp, " 4=%d", -233);
  735. }
  736. fprintf(pp, " 5=1"); // bias_term
  737. std::vector<float> v = get_attr_af(W);
  738. std::vector<float> bv = get_attr_af(B);
  739. // reorder h-w-i-o to o-i-h-w
  740. {
  741. int quantize_tag = 0;
  742. fwrite(&quantize_tag, sizeof(int), 1, bp);
  743. float tmp;
  744. for (int p = 0; p < num_output; p++)
  745. {
  746. for (int q = 0; q < num_input; q++)
  747. {
  748. for (int i = 0; i < kernel_size_h; i++)
  749. {
  750. for (int j = 0; j < kernel_size_w; j++)
  751. {
  752. tmp = v[i * kernel_size_w * num_input * num_output + j * num_input * num_output + q * num_output + p];
  753. fwrite(&tmp, sizeof(float), 1, bp);
  754. }
  755. }
  756. }
  757. }
  758. }
  759. fwrite(bv.data(), sizeof(float), bv.size(), bp);
  760. }
  761. else if (op == "ncnn.KerasDense")
  762. {
  763. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  764. std::string bias_name = get_mlir_value_uniq_id(operation.getOperand(2));
  765. const mlir::Attribute& W = weights[weight_name];
  766. const mlir::Attribute& B = weights[bias_name];
  767. llvm::ArrayRef<int64_t> shape = W.getType().cast<mlir::RankedTensorType>().getShape();
  768. // assert(shape.size() == 2)
  769. // inch-outch
  770. int num_input = shape[0];
  771. int num_output = shape[1];
  772. int weight_data_size = shape[0] * shape[1];
  773. fprintf(pp, " 0=%d", num_output);
  774. fprintf(pp, " 1=1"); // bias_term
  775. fprintf(pp, " 2=%d", weight_data_size);
  776. std::vector<float> v = get_attr_af(W);
  777. std::vector<float> bv = get_attr_af(B);
  778. // reorder i-o to o-i
  779. {
  780. int quantize_tag = 0;
  781. fwrite(&quantize_tag, sizeof(int), 1, bp);
  782. float tmp;
  783. for (int p = 0; p < num_output; p++)
  784. {
  785. for (int q = 0; q < num_input; q++)
  786. {
  787. tmp = v[q * num_output + p];
  788. fwrite(&tmp, sizeof(float), 1, bp);
  789. }
  790. }
  791. }
  792. fwrite(bv.data(), sizeof(float), bv.size(), bp);
  793. }
  794. else if (op == "ncnn.KerasBatchNorm")
  795. {
  796. std::string gamma_name = get_mlir_value_uniq_id(operation.getOperand(1));
  797. std::string bias_name = get_mlir_value_uniq_id(operation.getOperand(2));
  798. const mlir::Attribute& W = weights[gamma_name];
  799. const mlir::Attribute& B = weights[bias_name];
  800. std::vector<float> v = get_attr_af(W);
  801. std::vector<float> bv = get_attr_af(B);
  802. int channels = v.size();
  803. fprintf(pp, " 0=%d", channels);
  804. std::vector<float> mean(channels, 0.f);
  805. std::vector<float> var(channels, 1.f);
  806. fwrite(v.data(), sizeof(float), channels, bp);
  807. fwrite(mean.data(), sizeof(float), channels, bp);
  808. fwrite(var.data(), sizeof(float), channels, bp);
  809. fwrite(bv.data(), sizeof(float), channels, bp);
  810. }
  811. else if (op == "ncnn.InstanceNorm")
  812. {
  813. float eps = get_operation_attr_f(operation, "epsilon");
  814. fprintf(pp, " 0=0"); // channels
  815. fprintf(pp, " 1=%e", eps);
  816. fprintf(pp, " 2=0"); // affine
  817. }
  818. else if (op == "ncnn.InstanceNormAffine")
  819. {
  820. float eps = get_operation_attr_f(operation, "epsilon");
  821. std::string gamma_name = get_mlir_value_uniq_id(operation.getOperand(1));
  822. std::string beta_name = get_mlir_value_uniq_id(operation.getOperand(2));
  823. const mlir::Attribute& G = weights[gamma_name];
  824. const mlir::Attribute& B = weights[beta_name];
  825. std::vector<float> gv = get_attr_af(G);
  826. std::vector<float> bv = get_attr_af(B);
  827. int channels = gv.size();
  828. fprintf(pp, " 0=%d", channels);
  829. fprintf(pp, " 1=%e", eps);
  830. fprintf(pp, " 2=1"); // affine
  831. fwrite(gv.data(), sizeof(float), gv.size(), bp);
  832. fwrite(bv.data(), sizeof(float), bv.size(), bp);
  833. }
  834. else if (op == "ncnn.Swish")
  835. {
  836. // no param
  837. }
  838. else if (op == "tf.AddN")
  839. {
  840. int op_type = 1;
  841. fprintf(pp, " 0=%d", op_type);
  842. }
  843. else if (op == "tf.AddV2")
  844. {
  845. int op_type = 0;
  846. fprintf(pp, " 0=%d", op_type);
  847. }
  848. else if (op == "tf.AvgPool")
  849. {
  850. std::vector<int> ksize = get_operation_attr_ai(operation, "ksize");
  851. std::vector<int> strides = get_operation_attr_ai(operation, "strides");
  852. std::string padding = get_operation_attr_s(operation, "padding");
  853. fprintf(pp, " 0=1"); // avg pool
  854. if (ksize.size() == 4)
  855. {
  856. fprintf(pp, " 1=%d", ksize[2]);
  857. fprintf(pp, " 11=%d", ksize[1]);
  858. }
  859. if (strides.size() == 4)
  860. {
  861. fprintf(pp, " 2=%d", strides[2]);
  862. fprintf(pp, " 12=%d", strides[1]);
  863. }
  864. int pad_mode = 1;
  865. if (padding == "VALID")
  866. {
  867. pad_mode = 1;
  868. }
  869. else if (padding == "SAME")
  870. {
  871. pad_mode = 2;
  872. }
  873. fprintf(pp, " 5=%d", pad_mode);
  874. }
  875. else if (op == "tf.ConcatV2")
  876. {
  877. std::string axis_name = get_mlir_value_uniq_id(operation.getOperand(operation.getNumOperands() - 1));
  878. const mlir::Attribute& A = weights[axis_name];
  879. int axis = get_attr_ai(A)[0];
  880. // axis nhc to nhw
  881. // axis nhwc to nchw
  882. int dims = operation.getOperand(0).getType().cast<mlir::RankedTensorType>().getShape().size();
  883. if (dims == 2 && axis == 1)
  884. {
  885. axis = 0;
  886. }
  887. if (dims == 3 && axis == 1)
  888. {
  889. axis = 1;
  890. }
  891. if (dims == 3 && axis == 2)
  892. {
  893. axis = 0;
  894. }
  895. if (dims == 4 && axis == 1)
  896. {
  897. axis = 1;
  898. }
  899. if (dims == 4 && axis == 2)
  900. {
  901. axis = 2;
  902. }
  903. if (dims == 4 && axis == 3)
  904. {
  905. axis = 0;
  906. }
  907. fprintf(pp, " 0=%d", axis);
  908. }
  909. else if (op == "tf.Const")
  910. {
  911. // never reach here
  912. }
  913. else if (op == "tf.Conv2D")
  914. {
  915. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  916. const mlir::Attribute& W = weights[weight_name];
  917. llvm::ArrayRef<int64_t> shape = W.getType().cast<mlir::RankedTensorType>().getShape();
  918. // assert(shape.size() == 4)
  919. // kh-kw-inch-outch
  920. int kernel_size_h = shape[0];
  921. int kernel_size_w = shape[1];
  922. int num_input = shape[2];
  923. int num_output = shape[3];
  924. int weight_data_size = kernel_size_h * kernel_size_w * num_input * num_output;
  925. fprintf(pp, " 0=%d", num_output);
  926. fprintf(pp, " 1=%d", kernel_size_w);
  927. fprintf(pp, " 11=%d", kernel_size_h);
  928. fprintf(pp, " 6=%d", weight_data_size);
  929. std::vector<int> dilations = get_operation_attr_ai(operation, "dilations");
  930. std::vector<int> strides = get_operation_attr_ai(operation, "strides");
  931. std::string padding = get_operation_attr_s(operation, "padding");
  932. if (dilations.size() == 4)
  933. {
  934. fprintf(pp, " 2=%d", dilations[2]);
  935. fprintf(pp, " 12=%d", dilations[1]);
  936. }
  937. if (strides.size() == 4)
  938. {
  939. fprintf(pp, " 3=%d", strides[2]);
  940. fprintf(pp, " 13=%d", strides[1]);
  941. }
  942. if (padding == "EXPLICIT")
  943. {
  944. // nhwc = [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]
  945. std::vector<int> explicit_paddings = get_operation_attr_ai(operation, "explicit_paddings");
  946. fprintf(pp, " 4=%d", explicit_paddings[4]);
  947. fprintf(pp, " 15=%d", explicit_paddings[5]);
  948. fprintf(pp, " 14=%d", explicit_paddings[2]);
  949. fprintf(pp, " 16=%d", explicit_paddings[3]);
  950. }
  951. else if (padding == "VALID")
  952. {
  953. fprintf(pp, " 4=%d", 0);
  954. }
  955. else if (padding == "SAME")
  956. {
  957. fprintf(pp, " 4=%d", -233);
  958. }
  959. std::vector<float> v = get_attr_af(W);
  960. // reorder h-w-i-o to o-i-h-w
  961. {
  962. int quantize_tag = 0;
  963. fwrite(&quantize_tag, sizeof(int), 1, bp);
  964. float tmp;
  965. for (int p = 0; p < num_output; p++)
  966. {
  967. for (int q = 0; q < num_input; q++)
  968. {
  969. for (int i = 0; i < kernel_size_h; i++)
  970. {
  971. for (int j = 0; j < kernel_size_w; j++)
  972. {
  973. tmp = v[i * kernel_size_w * num_input * num_output + j * num_input * num_output + q * num_output + p];
  974. fwrite(&tmp, sizeof(float), 1, bp);
  975. }
  976. }
  977. }
  978. }
  979. }
  980. }
  981. else if (op == "tf.Conv2DBackpropInput")
  982. {
  983. std::string output_shape_name = get_mlir_value_uniq_id(operation.getOperand(0));
  984. const std::vector<int> output_shape = get_attr_ai(weights[output_shape_name]);
  985. // assert(output_shape.size() == 4)
  986. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  987. const mlir::Attribute& W = weights[weight_name];
  988. llvm::ArrayRef<int64_t> shape = W.getType().cast<mlir::RankedTensorType>().getShape();
  989. // assert(shape.size() == 4)
  990. // kh-kw-outch-inch
  991. int kernel_size_h = shape[0];
  992. int kernel_size_w = shape[1];
  993. int num_output = shape[2];
  994. int num_input = shape[3];
  995. int weight_data_size = kernel_size_h * kernel_size_w * num_input * num_output;
  996. fprintf(pp, " 0=%d", num_output);
  997. fprintf(pp, " 1=%d", kernel_size_w);
  998. fprintf(pp, " 11=%d", kernel_size_h);
  999. fprintf(pp, " 6=%d", weight_data_size);
  1000. std::vector<int> dilations = get_operation_attr_ai(operation, "dilations");
  1001. std::vector<int> strides = get_operation_attr_ai(operation, "strides");
  1002. std::string padding = get_operation_attr_s(operation, "padding");
  1003. if (dilations.size() == 4)
  1004. {
  1005. fprintf(pp, " 2=%d", dilations[2]);
  1006. fprintf(pp, " 12=%d", dilations[1]);
  1007. }
  1008. if (strides.size() == 4)
  1009. {
  1010. fprintf(pp, " 3=%d", strides[2]);
  1011. fprintf(pp, " 13=%d", strides[1]);
  1012. }
  1013. if (padding == "EXPLICIT")
  1014. {
  1015. // nhwc = [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]
  1016. std::vector<int> explicit_paddings = get_operation_attr_ai(operation, "explicit_paddings");
  1017. fprintf(pp, " 4=%d", explicit_paddings[4]);
  1018. fprintf(pp, " 15=%d", explicit_paddings[5]);
  1019. fprintf(pp, " 14=%d", explicit_paddings[2]);
  1020. fprintf(pp, " 16=%d", explicit_paddings[3]);
  1021. }
  1022. else if (padding == "VALID")
  1023. {
  1024. fprintf(pp, " 4=%d", 0);
  1025. }
  1026. else if (padding == "SAME")
  1027. {
  1028. fprintf(pp, " 4=%d", -233);
  1029. fprintf(pp, " 20=%d", output_shape[2]);
  1030. fprintf(pp, " 21=%d", output_shape[1]);
  1031. }
  1032. std::vector<float> v = get_attr_af(W);
  1033. // reorder h-w-o-i to o-i-h-w
  1034. {
  1035. int quantize_tag = 0;
  1036. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1037. float tmp;
  1038. for (int p = 0; p < num_output; p++)
  1039. {
  1040. for (int q = 0; q < num_input; q++)
  1041. {
  1042. for (int i = 0; i < kernel_size_h; i++)
  1043. {
  1044. for (int j = 0; j < kernel_size_w; j++)
  1045. {
  1046. tmp = v[i * kernel_size_w * num_output * num_input + j * num_output * num_input + p * num_input + q];
  1047. fwrite(&tmp, sizeof(float), 1, bp);
  1048. }
  1049. }
  1050. }
  1051. }
  1052. }
  1053. }
  1054. else if (op == "tf.DepthToSpace")
  1055. {
  1056. int block_size = get_operation_attr_i(operation, "block_size");
  1057. fprintf(pp, " 0=%d", block_size);
  1058. fprintf(pp, " 1=1"); // mode
  1059. }
  1060. else if (op == "tf.DepthwiseConv2dNative")
  1061. {
  1062. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1063. const mlir::Attribute& W = weights[weight_name];
  1064. llvm::ArrayRef<int64_t> shape = W.getType().cast<mlir::RankedTensorType>().getShape();
  1065. // assert(shape.size() == 4)
  1066. // kh-kw-inch-cm
  1067. int kernel_size_h = shape[0];
  1068. int kernel_size_w = shape[1];
  1069. int num_input = shape[2];
  1070. int channel_multiplier = shape[3];
  1071. int num_output = num_input * channel_multiplier;
  1072. int group = num_input;
  1073. int weight_data_size = kernel_size_h * kernel_size_w * num_input * channel_multiplier;
  1074. fprintf(pp, " 0=%d", num_output);
  1075. fprintf(pp, " 1=%d", kernel_size_w);
  1076. fprintf(pp, " 11=%d", kernel_size_h);
  1077. fprintf(pp, " 6=%d", weight_data_size);
  1078. fprintf(pp, " 7=%d", group);
  1079. std::vector<int> dilations = get_operation_attr_ai(operation, "dilations");
  1080. std::vector<int> strides = get_operation_attr_ai(operation, "strides");
  1081. std::string padding = get_operation_attr_s(operation, "padding");
  1082. if (dilations.size() == 4)
  1083. {
  1084. fprintf(pp, " 2=%d", dilations[2]);
  1085. fprintf(pp, " 12=%d", dilations[1]);
  1086. }
  1087. if (strides.size() == 4)
  1088. {
  1089. fprintf(pp, " 3=%d", strides[2]);
  1090. fprintf(pp, " 13=%d", strides[1]);
  1091. }
  1092. if (padding == "EXPLICIT")
  1093. {
  1094. // nhwc = [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]
  1095. std::vector<int> explicit_paddings = get_operation_attr_ai(operation, "explicit_paddings");
  1096. fprintf(pp, " 4=%d", explicit_paddings[4]);
  1097. fprintf(pp, " 15=%d", explicit_paddings[5]);
  1098. fprintf(pp, " 14=%d", explicit_paddings[2]);
  1099. fprintf(pp, " 16=%d", explicit_paddings[3]);
  1100. }
  1101. else if (padding == "VALID")
  1102. {
  1103. fprintf(pp, " 4=%d", 0);
  1104. }
  1105. else if (padding == "SAME")
  1106. {
  1107. fprintf(pp, " 4=%d", -233);
  1108. }
  1109. std::vector<float> v = get_attr_af(W);
  1110. // reorder h-w-i-cm to i-cm-h-w
  1111. {
  1112. int quantize_tag = 0;
  1113. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1114. float tmp;
  1115. for (int p = 0; p < num_input; p++)
  1116. {
  1117. for (int q = 0; q < channel_multiplier; q++)
  1118. {
  1119. for (int i = 0; i < kernel_size_h; i++)
  1120. {
  1121. for (int j = 0; j < kernel_size_w; j++)
  1122. {
  1123. tmp = v[i * kernel_size_w * channel_multiplier * num_input + j * channel_multiplier * num_input + p * channel_multiplier + q];
  1124. fwrite(&tmp, sizeof(float), 1, bp);
  1125. }
  1126. }
  1127. }
  1128. }
  1129. }
  1130. }
  1131. else if (op == "tf.Identity")
  1132. {
  1133. }
  1134. else if (op == "tf.LeakyRelu")
  1135. {
  1136. float alpha = get_operation_attr_f(operation, "alpha");
  1137. fprintf(pp, " 0=%e", alpha);
  1138. }
  1139. else if (op == "tf.MatMul")
  1140. {
  1141. int transpose_a = get_operation_attr_b(operation, "transpose_a");
  1142. int transpose_b = get_operation_attr_b(operation, "transpose_b");
  1143. if (transpose_a == 0 && transpose_b == 1)
  1144. {
  1145. // InnerProduct-like A * B + C
  1146. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1147. const mlir::Attribute& W = weights[weight_name];
  1148. llvm::ArrayRef<int64_t> shape = W.getType().cast<mlir::RankedTensorType>().getShape();
  1149. // assert(shape.size() == 2)
  1150. // inch-outch
  1151. int num_input = shape[0];
  1152. int num_output = shape[1];
  1153. int weight_data_size = shape[0] * shape[1];
  1154. fprintf(pp, " 0=%d", num_output);
  1155. fprintf(pp, " 2=%d", weight_data_size);
  1156. std::vector<float> v = get_attr_af(W);
  1157. // reorder i-o to o-i
  1158. {
  1159. int quantize_tag = 0;
  1160. fwrite(&quantize_tag, sizeof(int), 1, bp);
  1161. float tmp;
  1162. for (int p = 0; p < num_output; p++)
  1163. {
  1164. for (int q = 0; q < num_input; q++)
  1165. {
  1166. tmp = v[q * num_output + p];
  1167. fwrite(&tmp, sizeof(float), 1, bp);
  1168. }
  1169. }
  1170. }
  1171. }
  1172. else
  1173. {
  1174. // gemm
  1175. fprintf(pp, " 0=1.0"); // alpha
  1176. fprintf(pp, " 1=1.0"); // beta
  1177. fprintf(pp, " 2=%d", transpose_a);
  1178. fprintf(pp, " 3=%d", transpose_b);
  1179. }
  1180. }
  1181. else if (op == "tf.Maximum")
  1182. {
  1183. int op_type = 4;
  1184. fprintf(pp, " 0=%d", op_type);
  1185. }
  1186. else if (op == "tf.MaxPool")
  1187. {
  1188. std::vector<int> ksize = get_operation_attr_ai(operation, "ksize");
  1189. std::vector<int> strides = get_operation_attr_ai(operation, "strides");
  1190. std::string padding = get_operation_attr_s(operation, "padding");
  1191. fprintf(pp, " 0=0"); // max pool
  1192. if (ksize.size() == 4)
  1193. {
  1194. fprintf(pp, " 1=%d", ksize[2]);
  1195. fprintf(pp, " 11=%d", ksize[1]);
  1196. }
  1197. if (strides.size() == 4)
  1198. {
  1199. fprintf(pp, " 2=%d", strides[2]);
  1200. fprintf(pp, " 12=%d", strides[1]);
  1201. }
  1202. int pad_mode = 1;
  1203. if (padding == "VALID")
  1204. {
  1205. pad_mode = 1;
  1206. }
  1207. else if (padding == "SAME")
  1208. {
  1209. pad_mode = 2;
  1210. }
  1211. fprintf(pp, " 5=%d", pad_mode);
  1212. }
  1213. else if (op == "tf.Mean")
  1214. {
  1215. std::string reduction_indices_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1216. const mlir::Attribute& R = weights[reduction_indices_name];
  1217. std::vector<int> v = get_attr_ai(R);
  1218. int keep_dims = get_operation_attr_b(operation, "keep_dims");
  1219. if (keep_dims == 0 && v.size() == 2 && v[0] == 1 && v[1] == 2)
  1220. {
  1221. // global avg pooling style nhwc -> nc
  1222. int pool = 1;
  1223. int global_pool = 1;
  1224. fprintf(pp, " 0=%d", pool);
  1225. fprintf(pp, " 4=%d", global_pool);
  1226. }
  1227. else
  1228. {
  1229. // Reduction mean
  1230. fprintf(pp, " 0=3");
  1231. fprintf(pp, " 1=0"); // reduce_all
  1232. fprintf(pp, " -23303=%d", (int)v.size());
  1233. for (int i = 0; i < (int)v.size(); i++)
  1234. {
  1235. if (v[i] == 1)
  1236. fprintf(pp, ",1");
  1237. if (v[i] == 2)
  1238. fprintf(pp, ",2");
  1239. if (v[i] == 3)
  1240. fprintf(pp, ",0");
  1241. }
  1242. fprintf(pp, " 4=%d", keep_dims);
  1243. fprintf(pp, " 5=1");
  1244. }
  1245. }
  1246. else if (op == "tf.Minimum")
  1247. {
  1248. int op_type = 5;
  1249. fprintf(pp, " 0=%d", op_type);
  1250. }
  1251. else if (op == "tf.Mul")
  1252. {
  1253. int op_type = 2;
  1254. fprintf(pp, " 0=%d", op_type);
  1255. }
  1256. else if (op == "tf.Pad")
  1257. {
  1258. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1259. const mlir::Attribute& P = weights[weight_name];
  1260. std::vector<int> v = get_attr_ai(P);
  1261. // nhwc = [[0, 0], [pad_top, pad_bottom], [pad_left, pad_right], [0, 0]]
  1262. fprintf(pp, " 0=%d", v[2]);
  1263. fprintf(pp, " 1=%d", v[3]);
  1264. fprintf(pp, " 2=%d", v[4]);
  1265. fprintf(pp, " 3=%d", v[5]);
  1266. }
  1267. else if (op == "tf.Placeholder")
  1268. {
  1269. }
  1270. else if (op == "tf.Relu")
  1271. {
  1272. }
  1273. else if (op == "tf.Relu6")
  1274. {
  1275. float min = 0.f;
  1276. float max = 6.f;
  1277. fprintf(pp, " 0=%e", min);
  1278. fprintf(pp, " 1=%e", max);
  1279. }
  1280. else if (op == "tf.Reshape")
  1281. {
  1282. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1283. const mlir::Attribute& S = weights[weight_name];
  1284. std::vector<int> v = get_attr_ai(S);
  1285. int size = v.size();
  1286. // n h w c
  1287. // n h c
  1288. // n c
  1289. if (size == 4)
  1290. {
  1291. fprintf(pp, " 0=%d 1=%d 2=%d", v[2], v[1], v[3]);
  1292. }
  1293. if (size == 3)
  1294. {
  1295. fprintf(pp, " 0=%d 1=%d 2=-233", v[1], v[2]);
  1296. }
  1297. if (size == 2)
  1298. {
  1299. fprintf(pp, " 0=%d 1=-233 2=-233", v[1]);
  1300. }
  1301. // FIXME may not always be the case
  1302. fprintf(pp, " 3=1");
  1303. }
  1304. else if (op == "tf.ResizeBilinear")
  1305. {
  1306. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1307. const mlir::Attribute& P = weights[weight_name];
  1308. std::vector<int> size = get_attr_ai(P);
  1309. int align_corners = get_operation_attr_b(operation, "align_corners");
  1310. int half_pixel_centers = get_operation_attr_b(operation, "half_pixel_centers");
  1311. if (!(align_corners == 0 && half_pixel_centers == 1))
  1312. {
  1313. fprintf(stderr, "Unsupported ResizeBilinear align_corners %d half_pixel_centers %d !\n", align_corners, half_pixel_centers);
  1314. }
  1315. fprintf(pp, " 0=2"); // bilinear
  1316. fprintf(pp, " 3=%d 4=%d", size[1], size[0]);
  1317. }
  1318. else if (op == "tf.ResizeNearestNeighbor")
  1319. {
  1320. std::string weight_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1321. const mlir::Attribute& P = weights[weight_name];
  1322. std::vector<int> size = get_attr_ai(P);
  1323. int align_corners = get_operation_attr_b(operation, "align_corners");
  1324. int half_pixel_centers = get_operation_attr_b(operation, "half_pixel_centers");
  1325. if (!(align_corners == 0 && half_pixel_centers == 1))
  1326. {
  1327. fprintf(stderr, "Unsupported ResizeNearestNeighbor align_corners %d half_pixel_centers %d !\n", align_corners, half_pixel_centers);
  1328. }
  1329. fprintf(pp, " 0=1"); // nearest
  1330. fprintf(pp, " 3=%d 4=%d", size[1], size[0]);
  1331. }
  1332. else if (op == "tf.Sigmoid")
  1333. {
  1334. }
  1335. else if (op == "tf.Softmax")
  1336. {
  1337. }
  1338. else if (op == "tf.SpaceToDepth")
  1339. {
  1340. int block_size = get_operation_attr_i(operation, "block_size");
  1341. fprintf(pp, " 0=%d", block_size);
  1342. fprintf(pp, " 1=1"); // mode
  1343. }
  1344. else if (op == "tf.StridedSlice")
  1345. {
  1346. std::string begin_name = get_mlir_value_uniq_id(operation.getOperand(1));
  1347. std::string end_name = get_mlir_value_uniq_id(operation.getOperand(2));
  1348. std::string strides_name = get_mlir_value_uniq_id(operation.getOperand(3));
  1349. const mlir::Attribute& B = weights[begin_name];
  1350. const mlir::Attribute& E = weights[end_name];
  1351. const mlir::Attribute& S = weights[strides_name];
  1352. std::vector<int> begin = get_attr_ai(B);
  1353. std::vector<int> end = get_attr_ai(E);
  1354. std::vector<int> strides = get_attr_ai(S);
  1355. int begin_mask = get_operation_attr_i(operation, "begin_mask");
  1356. int end_mask = get_operation_attr_i(operation, "end_mask");
  1357. int ellipsis_mask = get_operation_attr_i(operation, "ellipsis_mask");
  1358. int new_axis_mask = get_operation_attr_i(operation, "new_axis_mask");
  1359. int shrink_axis_mask = get_operation_attr_i(operation, "shrink_axis_mask");
  1360. int dims = strides.size();
  1361. // assert strides == 1
  1362. for (int i = 0; i < dims; i++)
  1363. {
  1364. if (strides[i] != 1)
  1365. fprintf(stderr, "Unsupported StridedSlice strides !\n");
  1366. }
  1367. for (int i = 0; i < dims; i++)
  1368. {
  1369. // TODO strides[i] < 0
  1370. if (begin_mask & (1 << i))
  1371. {
  1372. begin[i] = 0;
  1373. }
  1374. if (end_mask & (1 << i))
  1375. {
  1376. end[i] = -233;
  1377. }
  1378. if (ellipsis_mask & (1 << i))
  1379. {
  1380. begin[i] = 0;
  1381. end[i] = -233;
  1382. }
  1383. }
  1384. if (new_axis_mask)
  1385. {
  1386. fprintf(stderr, "Unsupported StridedSlice new_axis_mask !\n");
  1387. }
  1388. if (shrink_axis_mask)
  1389. {
  1390. fprintf(stderr, "Unsupported StridedSlice shrink_axis_mask !\n");
  1391. }
  1392. // n h w c
  1393. // n h c
  1394. // n c
  1395. if (dims == 4)
  1396. {
  1397. fprintf(pp, " -23309=3,%d,%d,%d", begin[3], begin[1], begin[2]);
  1398. fprintf(pp, " -23310=3,%d,%d,%d", end[3], end[1], end[2]);
  1399. }
  1400. if (dims == 3)
  1401. {
  1402. fprintf(pp, " -23309=2,%d,%d", begin[2], begin[1]);
  1403. fprintf(pp, " -23310=2,%d,%d", end[2], end[1]);
  1404. }
  1405. if (dims == 2)
  1406. {
  1407. fprintf(pp, " -23309=1,%d", begin[1]);
  1408. fprintf(pp, " -23310=1,%d", end[1]);
  1409. }
  1410. }
  1411. else if (op == "tf.Sub")
  1412. {
  1413. int op_type = 1;
  1414. fprintf(pp, " 0=%d", op_type);
  1415. }
  1416. else if (op == "tf.Tanh")
  1417. {
  1418. }
  1419. #if 0
  1420. for (const mlir::NamedAttribute& attr : operation.getAttrs())
  1421. {
  1422. const mlir::Identifier& identifier = attr.first;
  1423. const mlir::Attribute& attr = attr.second;
  1424. fprintf(pp, " %s=", identifier.c_str());
  1425. if (attr.isa<mlir::AffineMapAttr>())
  1426. {
  1427. fprintf(pp, "AffineMap");
  1428. }
  1429. if (attr.isa<mlir::ArrayAttr>())
  1430. {
  1431. // fprintf(pp, "Array");
  1432. mlir::ArrayAttr a = attr.cast<mlir::ArrayAttr>();
  1433. int array_size = a.getValue().size();
  1434. for (int t=0; t<array_size; t++)
  1435. {
  1436. if (a[t].isa<mlir::IntegerAttr>())
  1437. {
  1438. int64_t ii = a[t].cast<mlir::IntegerAttr>().getInt();
  1439. fprintf(pp, "%lld,", ii);
  1440. }
  1441. }
  1442. }
  1443. if (attr.isa<mlir::BoolAttr>())
  1444. {
  1445. // fprintf(pp, "Bool");
  1446. mlir::BoolAttr a = attr.cast<mlir::BoolAttr>();
  1447. fprintf(pp, "%d", a.getValue() ? 1 : 0);
  1448. }
  1449. if (attr.isa<mlir::DictionaryAttr>())
  1450. {
  1451. fprintf(pp, "Dictionary");
  1452. }
  1453. if (attr.isa<mlir::FloatAttr>())
  1454. {
  1455. fprintf(pp, "Float");
  1456. }
  1457. if (attr.isa<mlir::IntegerAttr>())
  1458. {
  1459. fprintf(pp, "Integer");
  1460. }
  1461. if (attr.isa<mlir::IntegerSetAttr>())
  1462. {
  1463. fprintf(pp, "IntegerSet");
  1464. }
  1465. if (attr.isa<mlir::OpaqueAttr>())
  1466. {
  1467. fprintf(pp, "Opaque");
  1468. }
  1469. if (attr.isa<mlir::StringAttr>())
  1470. {
  1471. // fprintf(pp, "String");
  1472. mlir::StringAttr s = attr.cast<mlir::StringAttr>();
  1473. fprintf(pp, "%s", s.getValue().empty() ? "" : s.getValue().data());
  1474. }
  1475. if (attr.isa<mlir::SymbolRefAttr>())
  1476. {
  1477. fprintf(pp, "SymbolRef");
  1478. }
  1479. if (attr.isa<mlir::FlatSymbolRefAttr>())
  1480. {
  1481. fprintf(pp, "FlatSymbolRef");
  1482. }
  1483. if (attr.isa<mlir::TypeAttr>())
  1484. {
  1485. fprintf(pp, "Type");
  1486. }
  1487. if (attr.isa<mlir::UnitAttr>())
  1488. {
  1489. fprintf(pp, "Unit");
  1490. }
  1491. if (attr.isa<mlir::ElementsAttr>())
  1492. {
  1493. fprintf(pp, "Elements");
  1494. }
  1495. if (attr.isa<mlir::DenseElementsAttr>())
  1496. {
  1497. fprintf(pp, "DenseElements");
  1498. }
  1499. if (attr.isa<mlir::DenseFPElementsAttr>())
  1500. {
  1501. fprintf(pp, "DenseFPElements");
  1502. }
  1503. if (attr.isa<mlir::DenseIntElementsAttr>())
  1504. {
  1505. fprintf(pp, "DenseIntElements");
  1506. }
  1507. if (attr.isa<mlir::OpaqueElementsAttr>())
  1508. {
  1509. fprintf(pp, "OpaqueElements");
  1510. }
  1511. if (attr.isa<mlir::SparseElementsAttr>())
  1512. {
  1513. fprintf(pp, "SparseElements");
  1514. }
  1515. if (attr.isa<mlir::SplatElementsAttr>())
  1516. {
  1517. fprintf(pp, "SplatElements");
  1518. }
  1519. }
  1520. #endif
  1521. fprintf(pp, "\n");
  1522. for (int j = 0; j < num_output; j++)
  1523. {
  1524. std::string output_name = get_mlir_value_uniq_id(operation.getResult(j));
  1525. if (node_reference.find(output_name) != node_reference.end())
  1526. {
  1527. int refcount = node_reference[output_name];
  1528. if (refcount > 1)
  1529. {
  1530. char splitname[256];
  1531. sprintf(splitname, "splitncnn_%d", internal_split);
  1532. fprintf(pp, "%-16s %-24s %d %d", "Split", splitname, 1, refcount);
  1533. fprintf(pp, " %s", output_name.c_str());
  1534. for (int k = 0; k < refcount; k++)
  1535. {
  1536. fprintf(pp, " %s_splitncnn_%d", output_name.c_str(), k);
  1537. }
  1538. fprintf(pp, "\n");
  1539. internal_split++;
  1540. }
  1541. }
  1542. }
  1543. }
  1544. fclose(pp);
  1545. fclose(bp);
  1546. return 0;
  1547. }