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

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