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 59 kB

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