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.

convert.cc 64 kB

6 years ago
6 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719
  1. /**
  2. * Copyright 2019 Huawei Technologies Co., Ltd
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "transform/graph_ir/convert.h"
  17. #include <inttypes.h>
  18. #include <algorithm>
  19. #include <stack>
  20. #include "utils/utils.h"
  21. #include "frontend/operator/ops.h"
  22. #include "utils/log_adapter.h"
  23. #include "ir/graph_utils.h"
  24. #include "utils/symbolic.h"
  25. #include "utils/config_manager.h"
  26. #include "utils/convert_utils.h"
  27. #include "utils/ms_context.h"
  28. #include "transform/graph_ir/op_adapter_map.h"
  29. #include "ops/state_ops.h"
  30. #include "ops/array_ops.h"
  31. #include "ops/elewise_calculation_ops.h"
  32. #include "ops/math_ops.h"
  33. #ifdef ENABLE_GE
  34. #include "ops/save_ops.h"
  35. #endif
  36. namespace mindspore {
  37. namespace transform {
  38. using std::endl;
  39. using ge::Operator;
  40. using mindspore::kAnyValue;
  41. using std::make_shared;
  42. using std::shared_ptr;
  43. using std::string;
  44. using std::vector;
  45. using Variable = ge::op::Variable;
  46. using Constant = ge::op::Constant;
  47. using Assign = ge::op::Assign;
  48. using Data = ge::op::Data;
  49. // ---------------implement of DfGraphConvertor-------------
  50. PrimType GetCNodeFuncType(const CNodePtr cnode) {
  51. if (cnode->inputs().empty()) {
  52. return kPrimTypeUnknown;
  53. }
  54. AnfNodePtr valuenode = cnode->input(0);
  55. if (IsValueNode<Primitive>(valuenode)) {
  56. // check whether the valuenode is primitive
  57. return GetValueNode<PrimitivePtr>(valuenode)->prim_type();
  58. }
  59. return kPrimTypeUnknown;
  60. }
  61. bool IsCaseNode(const CNodePtr node) {
  62. if (!node->inputs().empty() && node->input(0)->isa<CNode>() &&
  63. GetCNodeFuncName(node->input(0)->cast<CNodePtr>()) == "switch_layer") {
  64. return true;
  65. }
  66. return false;
  67. }
  68. std::string GetCNodeTargetFuncName(const CNodePtr cnode) {
  69. if (IsCaseNode(cnode)) {
  70. return string(kNameCase);
  71. }
  72. auto name = GetCNodeFuncName(cnode);
  73. if (name == "switch_layer") {
  74. name = "";
  75. }
  76. return name;
  77. }
  78. OpAdapterPtr DfGraphConvertor::FindAdapter(const AnfNodePtr node, bool train) {
  79. if (node->isa<CNode>()) {
  80. auto cnode = node->cast<CNodePtr>();
  81. std::string name = kNameCustomOp;
  82. if (!IsCustomCNode(cnode)) {
  83. name = GetCNodeTargetFuncName(cnode);
  84. }
  85. auto it_adpt = OpAdapterMap::get().find(name);
  86. if (it_adpt != OpAdapterMap::get().end()) {
  87. return it_adpt->second->Get(train);
  88. }
  89. MS_LOG(EXCEPTION) << "Can't find OpAdapter for " << name;
  90. }
  91. if (node->isa<ValueNode>()) {
  92. return OpAdapterMap::get()[kNameConst]->Get(train);
  93. }
  94. if (node->isa<Parameter>()) {
  95. return OpAdapterMap::get()[kNameParam]->Get(train);
  96. }
  97. return OpAdapterPtr(nullptr);
  98. }
  99. void DfGraphConvertor::InitLoopVar(std::vector<ge::Operator> *init_input) {
  100. if (this->training_) {
  101. GeTensorDesc desc(GeShape(), ge::FORMAT_NCHW, ge::DT_INT64);
  102. auto var_iter_num = std::make_shared<Variable>("npu_runconfig/iterations_per_loop");
  103. auto var_loop_cond = std::make_shared<Variable>("npu_runconfig/loop_cond");
  104. auto var_one = std::make_shared<Variable>("npu_runconfig/one");
  105. auto var_zero = std::make_shared<Variable>("npu_runconfig/zero");
  106. (void)var_iter_num->update_output_desc_y(desc);
  107. (void)var_loop_cond->update_output_desc_y(desc);
  108. (void)var_one->update_output_desc_y(desc);
  109. (void)var_zero->update_output_desc_y(desc);
  110. vars_["npu_runconfig/iterations_per_loop"] = var_iter_num;
  111. vars_["npu_runconfig/loop_cond"] = var_loop_cond;
  112. vars_["npu_runconfig/one"] = var_one;
  113. vars_["npu_runconfig/zero"] = var_zero;
  114. int64_t value = 0;
  115. auto const_iter_num = std::make_shared<Constant>("const/npu_runconfig/iterations_per_loop");
  116. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  117. value = ConfigManager::GetInstance().iter_num();
  118. } else {
  119. MS_LOG(INFO) << "Run with normal(non-sink) mode, the iterator number will always be 1";
  120. value = 1;
  121. ConfigManager::GetInstance().set_iter_num(value);
  122. }
  123. value -= 1; // iteration start from 0, the max iteration number for n loop should be n-1
  124. (void)const_iter_num->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  125. auto const_loop_cond = std::make_shared<Constant>("const/npu_runconfig/loop_cond");
  126. value = 0;
  127. (void)const_loop_cond->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  128. auto const_one = std::make_shared<Constant>("const/npu_runconfig/one");
  129. value = 1;
  130. (void)const_one->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  131. auto const_zero = std::make_shared<Constant>("const/npu_runconfig/zero");
  132. value = 0;
  133. (void)const_zero->set_attr_value(GeTensor(desc, reinterpret_cast<uint8_t *>(&value), sizeof(int64_t)));
  134. (void)const_iter_num->update_output_desc_y(desc);
  135. (void)const_loop_cond->update_output_desc_y(desc);
  136. (void)const_one->update_output_desc_y(desc);
  137. (void)const_zero->update_output_desc_y(desc);
  138. auto assign_iter_num = std::make_shared<Assign>("assign/npu_runconfig/iterations_per_loop");
  139. (void)assign_iter_num->set_input_ref(*var_iter_num).set_input_value(*const_iter_num);
  140. auto assign_loop_cond = std::make_shared<Assign>("assign/npu_runconfig/loop_cond");
  141. (void)assign_loop_cond->set_input_ref(*var_loop_cond).set_input_value(*const_loop_cond);
  142. auto assign_one = std::make_shared<Assign>("assign/npu_runconfig/one");
  143. (void)assign_one->set_input_ref(*var_one).set_input_value(*const_one);
  144. auto assign_zero = std::make_shared<Assign>("assign/npu_runconfig/zero");
  145. (void)assign_zero->set_input_ref(*var_zero).set_input_value(*const_zero);
  146. init_input->push_back(*var_iter_num);
  147. init_input->push_back(*var_loop_cond);
  148. init_input->push_back(*var_one);
  149. init_input->push_back(*var_zero);
  150. init_ops_.push_back(var_iter_num);
  151. init_ops_.push_back(var_loop_cond);
  152. init_ops_.push_back(var_one);
  153. init_ops_.push_back(var_zero);
  154. init_ops_.push_back(const_iter_num);
  155. init_ops_.push_back(const_loop_cond);
  156. init_ops_.push_back(const_one);
  157. init_ops_.push_back(const_zero);
  158. init_ops_.push_back(assign_iter_num);
  159. init_ops_.push_back(assign_loop_cond);
  160. init_ops_.push_back(assign_one);
  161. init_ops_.push_back(assign_zero);
  162. }
  163. }
  164. OpAdapterPtr DfGraphConvertor::FindAdapter(const std::string &name, bool train) {
  165. auto it = OpAdapterMap::get().find(name);
  166. if (it != OpAdapterMap::get().end()) {
  167. return it->second->Get(train);
  168. }
  169. MS_LOG(EXCEPTION) << "Can't find OpAdapter for " << name;
  170. }
  171. void DfGraphConvertor::DrawParamInitSubGraph(const std::string &name, const AnfNodePtr &it) {
  172. // draw init subgraph
  173. init_sout_ << "op_assign" << it.get() << "[label=<";
  174. init_sout_ << "<table border='1' cellborder='1'>" << endl;
  175. init_sout_ << "<tr>";
  176. init_sout_ << "<td port='1'>resource</td>";
  177. init_sout_ << "<td port='2'>value</td>";
  178. init_sout_ << "</tr>" << endl;
  179. init_sout_ << "<tr><td colspan=\"2\">"
  180. << "\"assign_" << name << "\"</td></tr>" << endl;
  181. init_sout_ << "</table>> shape=plaintext]" << endl;
  182. init_sout_ << "param" << it.get() << "[shape=octagon, label=\"" << name << "\"]" << endl;
  183. init_sout_ << "const" << it.get() << "[label= \"" << name << "_const"
  184. << "\" shape=ellipse]" << endl;
  185. init_sout_ << "param" << it.get() << "->"
  186. << "op_assign" << it.get() << ":1" << endl;
  187. init_sout_ << "const" << it.get() << "->"
  188. << "op_assign" << it.get() << ":2" << endl;
  189. }
  190. void DfGraphConvertor::SetupParamInitSubGraph(const TensorOrderMap &tensors, std::vector<ge::Operator> *init_input) {
  191. DfGraphPtr init_graph = std::make_shared<DfGraph>("init");
  192. std::vector<AnfNodePtr> nodes = TopoSort(anf_graph_->get_return());
  193. for (auto &it : nodes) {
  194. if (it->isa<ValueNode>()) {
  195. if (IsValueNode<SymbolicKeyInstance>(it)) {
  196. auto symbolic = GetValueNode<SymbolicKeyInstancePtr>(it);
  197. auto name = std::static_pointer_cast<Parameter>(symbolic->node())->name();
  198. auto iter = vars_.find(name); // get correspoding varaible op
  199. if (iter != vars_.end()) {
  200. op_cache_[it.get()] = iter->second;
  201. // #ifdef DRAW_GE_GRAPH
  202. compute_sout_ << op_draw_name_[params_[name].get()] << " -> " << op_draw_name_[it.get()]
  203. << "[style=\"dotted\"]" << endl;
  204. // #endif
  205. }
  206. } else if (IsValueNode<RefKey>(it)) {
  207. auto refkey = GetValueNode<RefKeyPtr>(it);
  208. auto name = refkey->tag();
  209. auto iter = vars_.find(name); // get correspoding varaible op
  210. if (iter != vars_.end()) {
  211. op_cache_[it.get()] = iter->second;
  212. compute_sout_ << op_draw_name_[params_[name].get()] << " -> " << op_draw_name_[it.get()]
  213. << "[style=\"dotted\"]" << endl;
  214. }
  215. }
  216. }
  217. }
  218. for (auto &it : tensors) {
  219. if (vars_.find(it.first) == vars_.end()) {
  220. MS_LOG(WARNING) << "Init parameter " << it.first << " didn't appear in graph.";
  221. vars_[it.first] = nullptr;
  222. }
  223. }
  224. // set up init sub graph
  225. if (init_input->size()) {
  226. // init sub graph needs no input
  227. MS_LOG(INFO) << "Build data init subgraph.";
  228. (void)init_graph->SetInputs(*init_input);
  229. this->init_graph_ = init_graph;
  230. } else {
  231. this->init_graph_ = nullptr;
  232. }
  233. }
  234. void DfGraphConvertor::MakeDatasetHandler(const std::string &name, const size_t &input_idx, const AnfNodePtr &it) {
  235. MS_LOG(INFO) << "The " << name << " is the " << input_idx << "(st/nd/th) input";
  236. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  237. auto getnext_idx = static_cast<int64_t>(input_idx);
  238. DatasetGraphParam param = ConfigManager::GetInstance().dataset_param();
  239. if (!param.input_indexes().empty() && input_idx <= param.input_indexes().size()) {
  240. getnext_idx = param.input_indexes()[input_idx] - 1; // input_idx start from 0.
  241. MS_LOG(INFO) << "remap input_index:" << input_idx << " to getnext_index:" << getnext_idx << ".";
  242. }
  243. // use iterator_getnext op with output_name instead of data op in BuildGraph.
  244. out_handle_cache_[it.get()] = OutHandler(dataset_iter_getnext_, "y" + std::to_string(getnext_idx));
  245. }
  246. }
  247. void DfGraphConvertor::SetupBroadcast(const std::shared_ptr<HcomBroadcast> &broadcast,
  248. const std::vector<GeTensorDesc> &broadcast_desc,
  249. const DfGraphPtr &broadcast_graph, std::vector<ge::Operator> broadcast_input) {
  250. MS_LOG(INFO) << "build broadcast subgraph";
  251. if (broadcast_desc.size() != broadcast_input.size()) {
  252. MS_LOG(EXCEPTION) << "Desc number of BroadCast is not equal to number of Input";
  253. }
  254. (void)broadcast->create_dynamic_input_x(static_cast<unsigned int>(broadcast_input.size()));
  255. (void)broadcast->create_dynamic_output_y(static_cast<unsigned int>(broadcast_desc.size()));
  256. for (unsigned int i = 0; i < broadcast_input.size(); i++) {
  257. (void)broadcast->set_dynamic_input_x(i, broadcast_input[i]);
  258. (void)broadcast->update_dynamic_output_desc_y(i, broadcast_desc[i]);
  259. }
  260. (void)broadcast_graph->SetInputs(broadcast_input);
  261. this->broadcast_graph_ = broadcast_graph;
  262. }
  263. void DfGraphConvertor::InitParamWithData(const TensorOrderMap &tensors) {
  264. int index = 0;
  265. std::vector<Operator> init_input;
  266. for (auto it : tensors) {
  267. std::string name = it.first;
  268. auto node_itor = params_.find(name);
  269. // if name not in params_, create a node in graph
  270. if (node_itor == params_.end()) {
  271. MS_LOG(WARNING) << name << " is not in params, and create a new node.";
  272. ParameterPtr param = std::make_shared<Parameter>(nullptr);
  273. name = name + "_temp";
  274. param->set_name(name);
  275. (void)ConvertParameter(param);
  276. node_itor = params_.find(name);
  277. }
  278. auto node = node_itor->second;
  279. auto op_itor = op_cache_.find(node.get());
  280. if (op_itor == op_cache_.end()) {
  281. MS_LOG(EXCEPTION) << "Can not find op for node " << node->ToString() << ".";
  282. }
  283. auto adpt = FindAdapter(kNameParam, training_);
  284. if (adpt == nullptr) continue;
  285. auto param_op = adpt->generate(name + "_data");
  286. MS_LOG(INFO) << "Add parameter " << name << " as input, index " << index << ".";
  287. if (!training_) {
  288. auto adpt_const = FindAdapter(kNameConst, training_);
  289. if (adpt_const == nullptr) continue;
  290. auto const_op = adpt_const->generate(name + "_const");
  291. (void)adpt_const->setAttr(const_op, "value", it.second);
  292. auto const_op_desc = TransformUtil::GetGeTensorDesc(it.second->shape_c(), it.second->data_type(), kOpFormat_NCHW);
  293. if (const_op_desc == nullptr) {
  294. MS_LOG(ERROR) << "Create variable " << name << " ouptut descriptor failed!";
  295. continue;
  296. }
  297. (void)std::static_pointer_cast<Constant>(const_op)->update_output_desc_y(*const_op_desc);
  298. vars_[name] = const_op;
  299. op_itor->second = const_op;
  300. continue;
  301. }
  302. // create tensor descriptor for output descriptor
  303. auto desc = TransformUtil::GetGeTensorDesc(it.second->shape_c(), it.second->data_type(), kOpFormat_NCHW);
  304. if (desc == nullptr) {
  305. MS_LOG(ERROR) << "Create variable " << name << " ouptut descriptor failed!";
  306. continue;
  307. }
  308. // we need three variable ops for each graph with same name
  309. // build init subgraph
  310. if (it.second->is_init() == 0) {
  311. (void)std::static_pointer_cast<Data>(param_op)->set_attr_index(index++);
  312. auto init_var = std::make_shared<Variable>(name);
  313. auto assign_op = std::make_shared<Assign>("assign_" + name);
  314. (void)init_var->update_output_desc_y(*desc);
  315. (void)assign_op->set_input_ref(*init_var).set_input_value(*param_op);
  316. init_input.push_back(*init_var);
  317. init_ops_.push_back(param_op);
  318. init_ops_.push_back(assign_op);
  319. init_ops_.push_back(init_var);
  320. }
  321. auto variable = std::make_shared<Variable>(name);
  322. (void)variable->update_output_desc_y(*desc);
  323. // do not use read variable while variable sink
  324. MS_LOG(DEBUG) << "InitParam, op_name = " << name << ", var = " << variable->GetName() << ".";
  325. op_itor->second = variable; // replace parameter with variable
  326. vars_[name] = variable; // prevent the variable operator from being freed
  327. DrawParamInitSubGraph(name, node);
  328. }
  329. InitLoopVar(&init_input);
  330. SetupParamInitSubGraph(tensors, &init_input);
  331. }
  332. // convert all parameter need initialize to variable
  333. DfGraphConvertor &DfGraphConvertor::InitParam(const TensorOrderMap &tensors) {
  334. size_t input_idx = 0;
  335. if (error_ != 0) {
  336. return *this;
  337. }
  338. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  339. error_ = INVALID_ARGUMENT;
  340. MS_LOG(ERROR) << "Invalid AnfGraph in InitParam.";
  341. return *this;
  342. }
  343. // Processing input with MakeDatasetHandler
  344. for (auto &it : anf_graph_->parameters()) {
  345. auto op_itor = op_cache_.find(it.get()); // converted node
  346. if (it->isa<Parameter>() && op_itor != op_cache_.end()) {
  347. string name = std::static_pointer_cast<Parameter>(it)->name();
  348. auto tensor_itor = tensors.find(name); // in init value map
  349. if (tensor_itor == tensors.end()) {
  350. DfGraphConvertor::MakeDatasetHandler(name, input_idx, it);
  351. input_idx++;
  352. }
  353. }
  354. }
  355. InitParamWithData(tensors);
  356. init_sout_ << "}" << endl;
  357. return *this;
  358. }
  359. #if (defined ENABLE_GE)
  360. void DfGraphConvertor::BuildSaveCheckpointGraph() {
  361. std::vector<Operator> graph_inputs;
  362. ge::op::Save save_op("save_parms");
  363. int save_op_is_active = 0;
  364. size_t index = 0;
  365. string name;
  366. int32_t count_size = std::count_if(vars_.begin(), vars_.end(), [](const std::pair<std::string, OperatorPtr> &it) {
  367. return (it.second == nullptr || it.first.find("/") != std::string::npos);
  368. });
  369. (void)save_op.create_dynamic_input_tensors(vars_.size() - static_cast<size_t>(count_size));
  370. // for each "parameter" in anf graph excluding "input"
  371. for (const auto &it : vars_) {
  372. name = it.first;
  373. if (it.second == nullptr || name.find("/") != std::string::npos) continue;
  374. Variable variable(name);
  375. (void)variable.update_output_desc_y(it.second->GetOutputDesc(0));
  376. (void)save_op.set_dynamic_input_tensors(index++, variable);
  377. graph_inputs.push_back(variable);
  378. if (save_op_is_active == 0) {
  379. checkpoint_sout_ << "op_save" << &save_op << "[label=<";
  380. checkpoint_sout_ << "<table border='1' cellborder='1'>" << endl;
  381. checkpoint_sout_ << "<tr><td port='1'>tensor</td></tr>" << endl;
  382. checkpoint_sout_ << "<tr><td colspan=\"1\">"
  383. << "\"saveop"
  384. << "\"</td></tr>" << endl;
  385. checkpoint_sout_ << "</table>> shape=plaintext]" << endl;
  386. }
  387. checkpoint_sout_ << "param" << it.second << "[shape=octagon, label=\"" << name << "\"]" << endl;
  388. checkpoint_sout_ << "param" << it.second << "->"
  389. << "op_save" << &save_op << ":1" << endl;
  390. save_op_is_active = 1;
  391. }
  392. if (save_op_is_active) {
  393. std::vector<Operator> graph_output;
  394. graph_output.emplace_back(save_op);
  395. DfGraphPtr checkpoint_graph = std::make_shared<DfGraph>("checkpoint");
  396. (void)checkpoint_graph->SetInputs(graph_inputs);
  397. (void)checkpoint_graph->SetOutputs(graph_output);
  398. this->save_ckp_graph_ = checkpoint_graph;
  399. } else {
  400. this->save_ckp_graph_ = nullptr;
  401. }
  402. checkpoint_sout_ << "}" << endl;
  403. return;
  404. }
  405. #endif
  406. DfGraphConvertor &DfGraphConvertor::GenerateBroadcastGraph(const TensorOrderMap &tensors) {
  407. if (error_ != 0) {
  408. return *this;
  409. }
  410. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  411. error_ = INVALID_ARGUMENT;
  412. MS_LOG(ERROR) << "Invalid AnfGraph in generate broadcast graph";
  413. return *this;
  414. }
  415. DfGraphPtr broadcast_graph = std::make_shared<DfGraph>("broadcast");
  416. // collect the operators create for broadcast sub graph, in order to avoid auto release
  417. std::vector<Operator> broadcast_input;
  418. std::vector<GeTensorDesc> broadcast_desc;
  419. auto broadcast = std::make_shared<HcomBroadcast>("broadcast_parameter");
  420. (void)broadcast->set_attr_root_rank(0);
  421. (void)broadcast->set_attr_group("hccl_world_group");
  422. broadcast_ops_.push_back(broadcast);
  423. // find every parameter, build broadcast subgraph (or initialize the parameter with constant)
  424. for (auto &it : anf_graph_->parameters()) {
  425. auto op_itor = op_cache_.find(it.get()); // converted node
  426. if (it->isa<Parameter>() && op_itor != op_cache_.end()) {
  427. string name = std::static_pointer_cast<Parameter>(it)->name();
  428. auto tensor_itor = tensors.find(name); // in init tensor map
  429. if (tensor_itor != tensors.end()) {
  430. auto tensor = tensor_itor->second;
  431. auto shape_ge = tensor->shape_c();
  432. // create tensor descriptor for output descriptor
  433. auto desc = TransformUtil::GetGeTensorDesc(shape_ge, tensor->data_type(), kOpFormat_NCHW);
  434. if (desc == nullptr) {
  435. MS_LOG(ERROR) << "Create variable " << name << " ouptut descriptor failed!";
  436. continue;
  437. }
  438. // build broadcast subgraph
  439. if (distribute_) {
  440. auto broadcast_var = std::make_shared<Variable>(name);
  441. (void)broadcast_var->update_output_desc_y(*desc);
  442. broadcast_input.push_back(*broadcast_var);
  443. broadcast_desc.push_back(*desc);
  444. broadcast_ops_.push_back(broadcast_var);
  445. }
  446. }
  447. }
  448. }
  449. // set up broadcast sub graph
  450. if (!broadcast_input.empty()) {
  451. DfGraphConvertor::SetupBroadcast(broadcast, broadcast_desc, broadcast_graph, broadcast_input);
  452. } else {
  453. this->broadcast_graph_ = nullptr;
  454. }
  455. return *this;
  456. }
  457. DfGraphConvertor &DfGraphConvertor::GenerateCheckpointGraph() {
  458. if (error_ != 0) {
  459. MS_LOG(ERROR) << "Generate checkpoint graph failed, found error code " << error_ << ".";
  460. return *this;
  461. }
  462. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  463. error_ = INVALID_ARGUMENT;
  464. MS_LOG(ERROR) << "Invalid AnfGraph in GenerateCheckpointGraph";
  465. return *this;
  466. }
  467. #if (defined ENABLE_GE)
  468. BuildSaveCheckpointGraph();
  469. // Restoring from checkpoint file is done by pyfront, not in graph now.
  470. #endif
  471. return *this;
  472. }
  473. DfGraphConvertor &DfGraphConvertor::ConvertAllNode() {
  474. if (error_ != 0) {
  475. return *this;
  476. }
  477. if (anf_graph_ == nullptr || anf_graph_->output() == nullptr) {
  478. MS_LOG(ERROR) << "Invalid AnfGraph";
  479. error_ = FAILED;
  480. return *this;
  481. }
  482. compute_sout_.clear();
  483. compute_sout_ << "digraph {" << endl;
  484. init_sout_.clear();
  485. init_sout_ << "digraph {" << endl;
  486. checkpoint_sout_.clear();
  487. checkpoint_sout_ << "digraph {" << endl;
  488. restore_checkpoint_sout_.clear();
  489. restore_checkpoint_sout_ << "digraph {" << endl;
  490. // Convert all anf node to Operator
  491. MS_LOG(DEBUG) << "convert all node";
  492. std::vector<AnfNodePtr> nodes = TopoSort(anf_graph_->get_return());
  493. for (auto &it : nodes) {
  494. (void)Convert(it);
  495. if (this->error_ != 0) {
  496. MS_LOG(ERROR) << "failed to convert node: " << it->DebugString() << ".";
  497. }
  498. }
  499. // Create dataset iterator and iterator_getnext node
  500. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  501. DatasetGraphParam param = ConfigManager::GetInstance().dataset_param();
  502. MS_LOG(INFO) << "Dataset param is " << param.ToString() << ".";
  503. // GetNext
  504. auto iter_getnext_op = make_shared<ge::op::GetNext>("get_next_tmp");
  505. (void)iter_getnext_op->set_attr_output_types(param.ge_types());
  506. (void)iter_getnext_op->set_attr_output_shapes(param.shapes());
  507. (void)iter_getnext_op->set_attr_channel_name(param.queue_name());
  508. // save iter_getnext_op for later use
  509. dataset_iter_getnext_ = iter_getnext_op;
  510. }
  511. // return the data flow graph
  512. return *this;
  513. }
  514. void DfGraphConvertor::TraceOutputFromTupleGetItem(const AnfNodePtr &anf_out) {
  515. auto it = out_handle_cache_.find(anf_out.get());
  516. if (it != out_handle_cache_.end()) {
  517. OutHandler handle = it->second;
  518. auto op = handle.op;
  519. if (op != nullptr) {
  520. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType() << ", out_name: " << handle.out;
  521. graph_outputs_.emplace_back(std::make_pair(*op, handle.out));
  522. } else {
  523. MS_LOG(EXCEPTION) << "tuple_getitem: " << anf_out->fullname_with_scope() << " is not converted";
  524. }
  525. } else {
  526. // invalid tuple_getitem e.g. tuple_getitem(tuple_getitem())/tuple_getitem(depend())/tuple_getitem(make_tuple())
  527. MS_LOG(WARNING) << "Invalid tuple_getitem: " << anf_out->fullname_with_scope();
  528. }
  529. }
  530. void DfGraphConvertor::TraceOutput(const AnfNodePtr node) {
  531. AnfNodePtr anf_out = node;
  532. AnfNodePtr pre_node = nullptr;
  533. // Trace value node
  534. if (node->isa<ValueNode>()) {
  535. auto op = Convert(anf_out);
  536. graph_outputs_.emplace_back(std::make_pair(*op, ""));
  537. AddGraphConstInput(op);
  538. return;
  539. }
  540. // Trace Parameter node
  541. TraceOutputFromParameter(anf_out);
  542. // Then trace cnode
  543. if (!node->isa<CNode>()) {
  544. return;
  545. }
  546. // trace tuple_getitem
  547. while (anf_out->isa<CNode>() && IsPrimitiveCNode(anf_out, prim::kPrimTupleGetItem)) {
  548. pre_node = anf_out;
  549. anf_out = anf_out->cast<CNodePtr>()->input(1);
  550. }
  551. // trace every element of make_tuple
  552. auto c = anf_out->cast<CNodePtr>();
  553. std::string name = "";
  554. if (anf_out->isa<CNode>()) {
  555. name = GetCNodeTargetFuncName(c);
  556. }
  557. if (name == "make_tuple") {
  558. for (unsigned int i = 1; i < c->inputs().size(); i++) {
  559. TraceOutput(c->input(i));
  560. }
  561. } else if (name == "Depend") {
  562. if (c->inputs().size() < 3) { // "Depend" primitive have 3 inputs
  563. MS_LOG(EXCEPTION) << "length of inputs is " << c->inputs().size() << ", which is less than 3";
  564. }
  565. TraceOutput(c->input(1));
  566. } else if (name == "tuple_getitem") {
  567. TraceOutputFromTupleGetItem(anf_out);
  568. } else {
  569. // add outputs;
  570. auto op = Convert(anf_out);
  571. std::string index;
  572. if (op != nullptr) {
  573. if ((pre_node != nullptr) && IsPrimitiveCNode(pre_node, prim::kPrimTupleGetItem)) {
  574. auto item = out_handle_cache_.find(pre_node.get());
  575. if (item != out_handle_cache_.end()) {
  576. index = item->second.out;
  577. } else {
  578. MS_LOG(WARNING) << "Can't get operater: " << anf_out->fullname_with_scope() << " 's output item";
  579. }
  580. }
  581. MS_LOG(INFO) << "Add graph output: " << anf_out->fullname_with_scope() << ":" << index;
  582. graph_outputs_.emplace_back(make_pair(*op, index));
  583. }
  584. }
  585. }
  586. void DfGraphConvertor::TraceOutputFromParameter(const AnfNodePtr &anf_out) {
  587. if (anf_out->isa<Parameter>()) {
  588. MS_LOG(INFO) << "Add graph output: " << anf_out->fullname_with_scope();
  589. auto it = out_handle_cache_.find(anf_out.get());
  590. if (it != out_handle_cache_.end()) {
  591. // For dataset graph mode, input parameter is converted to a "iterator_get_next:yn" OutHandler.
  592. OutHandler handle = it->second;
  593. auto op = handle.op;
  594. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType() << ", out_name: " << handle.out;
  595. graph_outputs_.emplace_back(make_pair(*op, handle.out));
  596. } else {
  597. // common parameter case
  598. auto op = Convert(anf_out);
  599. if (op != nullptr) {
  600. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType();
  601. graph_outputs_.emplace_back(std::make_pair(*op, ""));
  602. }
  603. }
  604. }
  605. }
  606. void SetupDatasetIterGetNextNode(const OperatorPtr &op) {
  607. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  608. DatasetGraphParam param = ConfigManager::GetInstance().dataset_param();
  609. size_t output_num = param.ge_types().size();
  610. MS_LOG(INFO) << "Set iterator_getnext op's output num = " << output_num << ".";
  611. // set iterator_getnext op's output num
  612. shared_ptr<ge::op::GetNext> iter_getnext = std::static_pointer_cast<ge::op::GetNext>(op);
  613. (void)iter_getnext->create_dynamic_output_y(static_cast<unsigned int>(output_num));
  614. for (uint32_t i = 0; i < output_num; i++) {
  615. ge::TensorDesc desc(GeShape(param.shapes()[i]), ge::FORMAT_NCHW, (ge::DataType)param.ge_types()[i]);
  616. // we don't SetRealDimCnt here since GE do not use this output's real-dim
  617. (void)iter_getnext->update_dynamic_output_desc_y((i), desc);
  618. }
  619. }
  620. return;
  621. }
  622. void DfGraphConvertor::SetSubgraph(AnfNodePtr node) {
  623. if (!node->isa<CNode>()) {
  624. return;
  625. }
  626. auto cnode = node->cast<CNodePtr>();
  627. if (!IsCaseNode(cnode)) {
  628. return;
  629. }
  630. std::vector<AnfNodePtr> case_inputs;
  631. for (size_t i = 1; i < cnode->inputs().size(); i++) {
  632. case_inputs.emplace_back(cnode->input(i));
  633. }
  634. std::shared_ptr<std::vector<DfGraph>> branches = std::make_shared<std::vector<DfGraph>>();
  635. auto bnode = cnode->input(0)->cast<CNodePtr>()->input(2)->cast<CNodePtr>();
  636. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  637. auto branch_node = bnode->input(i)->cast<CNodePtr>();
  638. for (size_t j = 2; j < branch_node->inputs().size(); j++) {
  639. if (std::find(case_inputs.begin(), case_inputs.end(), branch_node->input(j)) == case_inputs.end()) {
  640. case_inputs.emplace_back(branch_node->input(j));
  641. }
  642. }
  643. }
  644. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  645. ProcessSubgraph(bnode->input(i), case_inputs);
  646. }
  647. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  648. branches->emplace_back(branches_map_[bnode->input(i).get()]);
  649. }
  650. if (op_cache_.find(node.get()) == op_cache_.end()) {
  651. return;
  652. }
  653. OpAdapterPtr adpt = FindAdapter(node, training_);
  654. if (nullptr == adpt) {
  655. MS_LOG(DEBUG) << "Not found adapter";
  656. return;
  657. }
  658. OperatorPtr op = Convert(node);
  659. adpt->setSubgraph(op, 0, branches);
  660. return;
  661. }
  662. void DfGraphConvertor::GetCaseNodeInput(const CNodePtr node, const CNodePtr input_node) {
  663. std::vector<AnfNodePtr> case_inputs;
  664. for (size_t i = 1; i < node->inputs().size(); i++) {
  665. case_inputs.emplace_back(node->input(i));
  666. }
  667. std::shared_ptr<std::vector<DfGraph>> branches = std::make_shared<std::vector<DfGraph>>();
  668. auto bnode = input_node->input(2)->cast<CNodePtr>();
  669. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  670. auto branch_node = bnode->input(i)->cast<CNodePtr>();
  671. for (size_t j = 2; j < branch_node->inputs().size(); j++) {
  672. if (std::find(case_inputs.begin(), case_inputs.end(), branch_node->input(j)) == case_inputs.end()) {
  673. case_inputs.emplace_back(branch_node->input(j));
  674. }
  675. }
  676. }
  677. const size_t case_index = 1;
  678. const size_t make_tuple_index = 2;
  679. AnfNodePtr case_index_iter = input_node->input(case_index);
  680. AnfNodePtr make_tuple_iter = input_node->input(make_tuple_index);
  681. auto make_tuple_node = make_tuple_iter->cast<CNodePtr>();
  682. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  683. for (size_t i = 0; i < case_inputs.size(); i++) {
  684. auto item = case_inputs[i];
  685. auto op = Convert(item);
  686. if (op != nullptr) {
  687. tuple_items->emplace_back(OutHandler(op, ""));
  688. } else if (out_handle_cache_.find(item.get()) != out_handle_cache_.end()) {
  689. tuple_items->push_back(out_handle_cache_[item.get()]);
  690. } else {
  691. MS_LOG(WARNING) << "This anf node is not supported as a case input: " << item->ToString();
  692. continue;
  693. }
  694. }
  695. tuple_out_handle_cache_[make_tuple_node.get()] = tuple_items;
  696. std::shared_ptr<std::vector<AnfNodePtr>> case_input_items = std::make_shared<std::vector<AnfNodePtr>>();
  697. case_input_items->emplace_back(case_index_iter);
  698. case_input_items->emplace_back(make_tuple_iter);
  699. case_input_handle_cache_[node.get()] = case_input_items;
  700. }
  701. DfGraphConvertor &DfGraphConvertor::BuildGraph() {
  702. SetupDatasetIterGetNextNode(dataset_iter_getnext_);
  703. if (error_ != 0) {
  704. return *this;
  705. }
  706. // Case node set input.
  707. std::vector<AnfNodePtr> nodes = ::mindspore::TopoSort(anf_graph_->get_return());
  708. for (auto &it : nodes) {
  709. if (it->isa<CNode>() && IsCaseNode(it->cast<CNodePtr>())) {
  710. auto node = it->cast<CNodePtr>();
  711. auto input_node = node->input(0)->cast<CNodePtr>();
  712. GetCaseNodeInput(node, input_node);
  713. }
  714. }
  715. // update tuple_out_handle_cache_
  716. for (auto it : tuple_out_handle_cache_) {
  717. std::size_t len = it.second->size();
  718. for (std::size_t i = 0; i < len; i++) {
  719. OutHandler handle = (*it.second)[i];
  720. if (handle.op) {
  721. string name = handle.op->GetName();
  722. if (vars_.count(name)) {
  723. OperatorPtr new_op = vars_[name];
  724. if (new_op != nullptr) {
  725. MS_LOG(INFO) << "update tuple_out_handle_cache_ " << name;
  726. (*it.second)[i] = OutHandler(new_op, handle.out);
  727. }
  728. }
  729. }
  730. }
  731. }
  732. // set up dependices
  733. MS_LOG(DEBUG) << "set up dependices";
  734. nodes = ::mindspore::TopoSort(anf_graph_->get_return());
  735. for (auto &it : nodes) {
  736. SetNodeInput(it);
  737. SetOpControlInput(it);
  738. SetSubgraph(it);
  739. UpdateOpDesc(it);
  740. }
  741. if (error_ == 0) {
  742. df_graph_ = make_shared<DfGraph>(anf_graph_->ToString());
  743. } else {
  744. return *this;
  745. }
  746. // set graph input according to the order from anf graph
  747. std::vector<Operator> inputs;
  748. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  749. inputs.push_back(*dataset_iter_getnext_);
  750. } else {
  751. auto params = anf_graph_->parameters();
  752. if (use_inputs_) {
  753. params = inputs_;
  754. auto anf_params = anf_graph_->parameters();
  755. for (size_t i = 0; i < params.size(); i++) {
  756. for (size_t j = 0; j < anf_params.size(); j++) {
  757. if (params[i]->ToString() == anf_params[j]->ToString()) {
  758. params[i] = anf_params[j];
  759. }
  760. }
  761. }
  762. }
  763. int index = 0;
  764. for (auto &it : params) {
  765. auto name = std::static_pointer_cast<Parameter>(it)->name();
  766. // the parameters which has not been converted to var
  767. if (vars_.find(name) == vars_.end()) {
  768. auto op = Convert(it);
  769. MS_EXCEPTION_IF_NULL(op);
  770. MS_LOG(INFO) << "add not var input " << it->ToString() << ", index " << index;
  771. if (op == nullptr) {
  772. MS_LOG(ERROR) << "Convert graph failed!";
  773. return *this;
  774. }
  775. UpdateDataOpDesc(it, op);
  776. MS_LOG(INFO) << "add input " << it->ToString() << ", index " << index;
  777. (void)std::static_pointer_cast<Data>(op)->set_attr_index(index++);
  778. inputs.push_back(*op);
  779. } else if (vars_[name] != nullptr) {
  780. MS_LOG(INFO) << "add var input " << it->ToString();
  781. auto op = Convert(it);
  782. MS_EXCEPTION_IF_NULL(op);
  783. inputs.push_back(*op);
  784. }
  785. }
  786. }
  787. MS_LOG(DEBUG) << "trace output";
  788. graph_outputs_.clear();
  789. TraceOutput(anf_graph_->get_return()->input(1));
  790. // Add const nodes as graph input for some operator work with constant
  791. MS_LOG(INFO) << "graph const input size: " << graph_const_inputs_.size();
  792. std::transform(graph_const_inputs_.begin(), graph_const_inputs_.end(), std::back_inserter(inputs),
  793. [](OperatorPtr x) { return *x; });
  794. MS_LOG(INFO) << "set graph input num: " << inputs.size();
  795. (void)df_graph_->SetInputs(inputs);
  796. // set graph output
  797. // set the value of finale return apply node as the output of dataflow graph
  798. MS_LOG(DEBUG) << "set output";
  799. MS_LOG(INFO) << "set graph output num: " << graph_outputs_.size();
  800. (void)df_graph_->SetOutputs(graph_outputs_);
  801. compute_sout_ << "}" << endl;
  802. // For the graph(e.g. eval_subgraph) whose IterNum is 1, donot set NeedIteration flag.
  803. if (ConfigManager::GetInstance().iter_num() > 1) {
  804. df_graph_->SetNeedIteration(true);
  805. }
  806. return *this;
  807. }
  808. void DfGraphConvertor::UpdateDataOpDesc(const AnfNodePtr &it, const OperatorPtr &op) const {
  809. auto node = std::static_pointer_cast<AnfNode>(it);
  810. if (node == nullptr) {
  811. MS_LOG(ERROR) << "Update data op descriptor failed! Invalid node.";
  812. return;
  813. }
  814. auto normal_shape_ptr = dyn_cast<abstract::Shape>(node->Shape());
  815. std::vector<int64_t> shape;
  816. if (normal_shape_ptr == nullptr) {
  817. MS_LOG(INFO) << "Invalid shape to update data op descriptor.";
  818. return;
  819. }
  820. shape = normal_shape_ptr->shape();
  821. if (node->Type() == nullptr) {
  822. MS_LOG(INFO) << "Invalid type to update data op descriptor.";
  823. return;
  824. }
  825. TypeId me_type = node->Type()->type_id();
  826. if (kObjectTypeTensorType == me_type) {
  827. me_type = dyn_cast<TensorType>(node->Type())->element()->type_id();
  828. }
  829. std::ostringstream buf;
  830. buf << "[" << shape << "]";
  831. MS_LOG(INFO) << "input shape is " << buf.str() << ", type is " << me_type;
  832. auto desc = TransformUtil::GetGeTensorDesc(shape, me_type, "NCHW");
  833. if (desc == nullptr) {
  834. MS_LOG(ERROR) << "Update data op descriptor failed! TensorDesc is null.";
  835. } else {
  836. (void)std::static_pointer_cast<Data>(op)->update_input_desc_x(*desc);
  837. (void)std::static_pointer_cast<Data>(op)->update_output_desc_y(*desc);
  838. }
  839. }
  840. DfGraphPtr DfGraphConvertor::GetComputeGraph() { return df_graph_; }
  841. DfGraphPtr DfGraphConvertor::GetInitGraph() { return init_graph_; }
  842. DfGraphPtr DfGraphConvertor::GetSaveCheckpointGraph() { return save_ckp_graph_; }
  843. DfGraphPtr DfGraphConvertor::GetBroadcastGraph() { return broadcast_graph_; }
  844. void DfGraphConvertor::SetOpControlInput(const AnfNodePtr node) {
  845. if (control_depend_cache_.find(node.get()) == control_depend_cache_.end()) {
  846. return;
  847. }
  848. std::vector<ControlEdge> control_edges = control_depend_cache_[node.get()];
  849. if ((control_edges.empty())) {
  850. MS_LOG(ERROR) << "Get control depend node's src or dest operator failed";
  851. return;
  852. }
  853. for (auto &item : control_edges) {
  854. (void)item.dest_op->AddControlInput(*item.src_op);
  855. }
  856. }
  857. const std::vector<std::string> trans_var_list = {string(kNameAssign), string(kNameAssignAdd), string(kNameAssignSub)};
  858. void DfGraphConvertor::SetOpInput(const OpAdapterPtr &adpt, const CNodePtr &node) {
  859. OperatorPtr src = Convert(node);
  860. int case_flag = 0;
  861. auto &inputs = node->inputs();
  862. size_t input_size = inputs.size();
  863. if (case_input_handle_cache_.find(node.get()) != case_input_handle_cache_.end()) {
  864. case_flag = 1;
  865. input_size = case_input_handle_cache_[node.get()]->size() + 1;
  866. }
  867. for (size_t i = 1; i < input_size; i++) {
  868. AnfNodePtr pred = nullptr;
  869. if (case_flag != 0) {
  870. pred = case_input_handle_cache_[node.get()]->at(i - 1);
  871. } else {
  872. pred = inputs[i];
  873. }
  874. while (pred->isa<CNode>() && GetCNodeTargetFuncName(pred->cast<CNodePtr>()) == "Depend") {
  875. pred = pred->cast<CNodePtr>()->input(1);
  876. }
  877. // skip the None input
  878. if (IsValueNode<None>(pred)) {
  879. continue;
  880. }
  881. // transform "Const" op to "Variable" op when the next node is "Assign" op.
  882. std::string c_name = GetCNodeTargetFuncName(node);
  883. auto pos = std::find(trans_var_list.begin(), trans_var_list.end(), c_name);
  884. if (!training_ && pos != trans_var_list.end() && pred->isa<Parameter>()) {
  885. std::string name = std::static_pointer_cast<Parameter>(pred)->name();
  886. auto op_itor = op_cache_.find(pred.get());
  887. if (op_itor == op_cache_.end()) {
  888. MS_LOG(EXCEPTION) << "Can not find op for node " << pred->ToString() << ".";
  889. }
  890. if (op_itor->second != nullptr &&
  891. (op_itor->second->GetOpType() == "Constant" || op_itor->second->GetOpType() == "Const") &&
  892. vars_.find(name) != vars_.end()) {
  893. auto variable = std::make_shared<Variable>(name);
  894. auto desc = vars_[name]->GetOutputDesc("y");
  895. (void)variable->update_output_desc_y(desc);
  896. MS_LOG(DEBUG) << "Trans to variable, var = " << variable->GetName() << ".";
  897. op_itor->second = variable; // replace parameter with variable
  898. vars_[name] = variable;
  899. }
  900. }
  901. // find in out_hadnle_cache_ first
  902. auto it = out_handle_cache_.find(pred.get());
  903. if (it != out_handle_cache_.end()) {
  904. int ret = adpt->setInput(src, SizeToInt(i), it->second);
  905. if (ret == 0) {
  906. if (pred->isa<CNode>() && GetCNodeTargetFuncName(pred->cast<CNodePtr>()) == "tuple_getitem") {
  907. compute_sout_ << op_draw_name_[pred->cast<CNodePtr>()->input(1).get()] << " -> " << op_draw_name_[node.get()]
  908. << ":" << i << endl;
  909. } else if (pred->isa<Parameter>()) {
  910. compute_sout_ << op_draw_name_[pred.get()] << " -> " << op_draw_name_[node.get()] << ":" << i << endl;
  911. } else {
  912. // don't draw anything.
  913. MS_LOG(INFO) << "DRAW_GE_GRAPH: Shouldn't have this case.";
  914. }
  915. AddGraphConstInput(it->second.op);
  916. }
  917. } else if (tuple_out_handle_cache_.find(pred.get()) != tuple_out_handle_cache_.end()) {
  918. std::shared_ptr<std::vector<OutHandler>> handler_vec = tuple_out_handle_cache_[pred.get()];
  919. int ret = adpt->setInput(src, SizeToInt(i), handler_vec);
  920. if ((ret == 0) && pred->isa<CNode>() && (pred->cast<CNodePtr>()->inputs().size() == handler_vec->size() + 1)) {
  921. for (unsigned int j = 0; j < handler_vec->size(); j++) {
  922. compute_sout_ << op_draw_name_[pred->cast<CNodePtr>()->input(j + 1).get()] << " -> "
  923. << op_draw_name_[node.get()] << ":" << i << endl;
  924. AddGraphConstInput(handler_vec->at(j).op);
  925. }
  926. } else {
  927. MS_LOG(WARNING) << "Convert tuple node setInput failed : " << node->ToString();
  928. }
  929. } else {
  930. auto op = Convert(pred);
  931. int ret = adpt->setInput(src, SizeToInt(i), op);
  932. if (ret == 0) {
  933. compute_sout_ << op_draw_name_[pred.get()] << " -> " << op_draw_name_[node.get()] << ":" << i << endl;
  934. AddGraphConstInput(op);
  935. }
  936. }
  937. }
  938. }
  939. void DfGraphConvertor::AddGraphConstInput(const OperatorPtr &op) {
  940. if (op->GetOpType() == "Constant" || op->GetOpType() == "Const") {
  941. graph_const_inputs_.push_back(op);
  942. }
  943. }
  944. void DfGraphConvertor::SetNodeInput(const AnfNodePtr node) {
  945. if (!node->isa<CNode>()) {
  946. return;
  947. }
  948. if (op_cache_.find(node.get()) == op_cache_.end()) {
  949. return;
  950. }
  951. auto cnode = node->cast<CNodePtr>();
  952. OpAdapterPtr adpt = FindAdapter(cnode, training_);
  953. if (adpt == nullptr) {
  954. error_ = NOT_FOUND;
  955. return;
  956. }
  957. // get Operator from op_cache_, use adapter to set Inputs
  958. DfGraphConvertor::SetOpInput(adpt, cnode);
  959. }
  960. void DfGraphConvertor::ProcessSubgraph(AnfNodePtr node, const std::vector<AnfNodePtr> &inputs) {
  961. if (!node->isa<CNode>() || GetCNodeFuncName(node->cast<CNodePtr>()) != "Partial") {
  962. return;
  963. }
  964. auto graph_node = node->cast<CNodePtr>()->input(1)->cast<ValueNodePtr>();
  965. FuncGraphPtr anf_graph = graph_node->value()->cast<FuncGraphPtr>();
  966. DfGraphConvertor convertor(anf_graph);
  967. convertor.use_inputs_ = true;
  968. convertor.inputs_ = inputs;
  969. (void)convertor.ConvertAllNode().BuildGraph();
  970. std::string name = graph_node->ToString() + "_ge_graph.dot";
  971. if (MsContext::GetInstance()->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG)) {
  972. convertor.DrawComputeGraph(name);
  973. }
  974. branches_map_[node.get()] = *(convertor.df_graph_);
  975. }
  976. // Update GE op's shape and type info
  977. void DfGraphConvertor::UpdateOpDesc(const AnfNodePtr node) {
  978. if (nullptr == node || !node->isa<CNode>()) {
  979. return;
  980. }
  981. if (op_cache_.find(node.get()) == op_cache_.end()) {
  982. return;
  983. }
  984. OpAdapterPtr adpt = FindAdapter(node, training_);
  985. if (adpt == nullptr) {
  986. error_ = NOT_FOUND;
  987. return;
  988. }
  989. // get Operator from op_cache_
  990. OperatorPtr op = Convert(node);
  991. adpt->updateOutputDesc(op, node->Shape(), node->Type(), node);
  992. }
  993. OperatorPtr DfGraphConvertor::Convert(const AnfNodePtr node) {
  994. if (node == nullptr) {
  995. MS_LOG(ERROR) << "node is nullptr";
  996. error_ = NOT_FOUND;
  997. return nullptr;
  998. }
  999. // find in cache
  1000. if (op_cache_.count(node.get())) {
  1001. return op_cache_[node.get()];
  1002. }
  1003. // do not convert primitive node
  1004. if (IsValueNode<Primitive>(node)) {
  1005. return nullptr;
  1006. }
  1007. // convert a new one
  1008. if (node->isa<CNode>()) {
  1009. return ConvertCNode(node->cast<CNodePtr>());
  1010. }
  1011. if (node->isa<Parameter>()) {
  1012. return ConvertParameter(node);
  1013. }
  1014. if (node->isa<ValueNode>()) {
  1015. return ConvertValueNode(node->cast<ValueNodePtr>());
  1016. }
  1017. MS_LOG(ERROR) << "Invalide AnfNode";
  1018. error_ = INVALID_ARGUMENT;
  1019. return nullptr;
  1020. }
  1021. void DfGraphConvertor::ConvertMakeTuple(const CNodePtr node) {
  1022. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  1023. // convert each tuple item to a OutHandler
  1024. for (size_t i = 1; i < node->inputs().size(); i++) {
  1025. AnfNodePtr item = node->input(i);
  1026. OperatorPtr op = Convert(item);
  1027. if (op != nullptr) {
  1028. tuple_items->emplace_back(OutHandler(op, ""));
  1029. } else if (out_handle_cache_.find(item.get()) != out_handle_cache_.end()) {
  1030. tuple_items->push_back(out_handle_cache_[item.get()]);
  1031. } else {
  1032. MS_LOG(WARNING) << "This anf node is not supported as a tuple item : " << item->ToString();
  1033. return;
  1034. }
  1035. }
  1036. MS_LOG(DEBUG) << "ConvertMakeTuple: " << node.get() << " " << tuple_items->size();
  1037. tuple_out_handle_cache_[node.get()] = tuple_items;
  1038. }
  1039. AnfNodePtr DfGraphConvertor::TraceTupleGetItem(const CNodePtr &node, uint64_t *index) {
  1040. const int TUPLE_GET_ITEM_INDEX = 2;
  1041. if (node->inputs().size() < 3) { // "tuple_getitem" primitive must have 3 inputs
  1042. MS_LOG(EXCEPTION) << "length of inputs of TupleGetItem is less than 3";
  1043. }
  1044. auto index_node = node->inputs()[TUPLE_GET_ITEM_INDEX];
  1045. if (!index_node->isa<ValueNode>()) {
  1046. error_ = INVALID_ARGUMENT;
  1047. MS_LOG(EXCEPTION) << "can't convert get item with non-constant index";
  1048. }
  1049. *index = LongToUlong(GetValue<int64_t>(GetValueNode(index_node)));
  1050. return node->inputs()[1];
  1051. }
  1052. AnfNodePtr DfGraphConvertor::TraceDepend(const CNodePtr &node) {
  1053. auto cnode = node->cast<CNodePtr>();
  1054. if (cnode->inputs().size() < 3) { // "Depend" primitive have 3 inputs
  1055. MS_LOG(EXCEPTION) << "length of inputs of depend is less than 3";
  1056. }
  1057. return cnode->inputs()[1];
  1058. }
  1059. AnfNodePtr DfGraphConvertor::TraceMakeTuple(const CNodePtr &node, uint64_t index) {
  1060. if (index + 1 >= node->inputs().size()) {
  1061. MS_LOG(EXCEPTION) << "length of make_tuple is less than index: " << index;
  1062. }
  1063. return node->inputs()[index + 1];
  1064. }
  1065. OutHandler DfGraphConvertor::GetHandler(const AnfNodePtr &node, const std::stack<uint64_t> &index_stack,
  1066. AnfNode *const draw_index) {
  1067. if (node == nullptr) {
  1068. MS_LOG(ERROR) << "Get nullptr while trace real op";
  1069. return OutHandler(nullptr, "");
  1070. }
  1071. std::ostringstream ss;
  1072. ss << "op" << node.get();
  1073. if (index_stack.empty()) {
  1074. op_draw_name_[draw_index] = ss.str();
  1075. return OutHandler(Convert(node), "");
  1076. } else {
  1077. OpAdapterPtr adpt = FindAdapter(node, training_);
  1078. if (nullptr == adpt) {
  1079. MS_LOG(ERROR) << "Can not get node output as adpt is nullptr!";
  1080. error_ = NOT_FOUND;
  1081. return OutHandler(nullptr, "");
  1082. }
  1083. OperatorPtr op = Convert(node);
  1084. if (op == nullptr) {
  1085. error_ = NOT_FOUND;
  1086. MS_LOG(ERROR) << "Can not convert node for trace real op";
  1087. return OutHandler(nullptr, "");
  1088. }
  1089. op_draw_name_[draw_index] = ss.str();
  1090. return adpt->getOutput(Convert(node), UintToInt(index_stack.top()));
  1091. }
  1092. }
  1093. // get the real operator through maketuple tuple_getitem depend
  1094. OutHandler DfGraphConvertor::TraceRealOp(AnfNodePtr node) {
  1095. bool flag = IsPrimitiveCNode(node, prim::kPrimTupleGetItem) || IsPrimitiveCNode(node, prim::kPrimMakeTuple) ||
  1096. IsPrimitiveCNode(node, prim::kPrimDepend);
  1097. std::stack<uint64_t> index_stack;
  1098. auto draw_index = node.get();
  1099. while (flag) {
  1100. flag = false;
  1101. if (IsPrimitiveCNode(node, prim::kPrimTupleGetItem)) {
  1102. uint64_t index;
  1103. node = TraceTupleGetItem(node->cast<CNodePtr>(), &index);
  1104. index_stack.push(index);
  1105. flag = true;
  1106. } else if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1107. if (index_stack.empty()) {
  1108. MS_LOG(ERROR) << "TraceRealOp find a make_tuple node";
  1109. return OutHandler(nullptr, "");
  1110. } else {
  1111. node = TraceMakeTuple(node->cast<CNodePtr>(), index_stack.top());
  1112. index_stack.pop();
  1113. flag = true;
  1114. }
  1115. } else if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  1116. node = TraceDepend(node->cast<CNodePtr>());
  1117. flag = true;
  1118. }
  1119. }
  1120. return GetHandler(node, index_stack, draw_index);
  1121. }
  1122. void DfGraphConvertor::ConvertTupleGetItem(const CNodePtr node) {
  1123. auto handle = TraceRealOp(node);
  1124. if (handle.op == nullptr) {
  1125. MS_LOG(ERROR) << "Failed to trace tuple get item";
  1126. return;
  1127. }
  1128. out_handle_cache_[node.get()] = handle;
  1129. }
  1130. // Get the real op for tuple_getitem through make tuple, or depend
  1131. AnfNodePtr DfGraphConvertor::GetRealOpNode(AnfNodePtr node) {
  1132. const int TUPLE_GET_ITEM_INDEX = 2;
  1133. if (IsPrimitiveCNode(node, prim::kPrimTupleGetItem)) {
  1134. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1135. if (node_inputs.size() != 3) { // "tuple_getitem" primitive must have 3 inputs
  1136. MS_LOG(ERROR) << "tuple get item node not correct!";
  1137. error_ = FAILED;
  1138. return node;
  1139. }
  1140. MS_EXCEPTION_IF_NULL(node_inputs[TUPLE_GET_ITEM_INDEX]);
  1141. if (!node_inputs[TUPLE_GET_ITEM_INDEX]->isa<ValueNode>()) {
  1142. error_ = INVALID_ARGUMENT;
  1143. MS_LOG(EXCEPTION) << "can't convert get item with non-constant index";
  1144. }
  1145. auto value_ptr = GetValueNode(node_inputs[TUPLE_GET_ITEM_INDEX])->cast<Int32ImmPtr>();
  1146. if (value_ptr == nullptr) {
  1147. MS_LOG(ERROR) << "Can not convert get item as value is nullptr!";
  1148. error_ = FAILED;
  1149. return node;
  1150. }
  1151. int64_t index = value_ptr->value();
  1152. // make_tuple apply inputs:make_tuple, [tuple_items,]
  1153. if (IsPrimitiveCNode(node_inputs[1], prim::kPrimMakeTuple)) {
  1154. auto tuple_inputs = node->cast<CNodePtr>()->inputs();
  1155. if (tuple_inputs.size() < IntToSize(index + 1)) {
  1156. MS_LOG(ERROR) << "make tuple input items node not correct! size:" << tuple_inputs.size()
  1157. << ", item index:" << index;
  1158. error_ = FAILED;
  1159. return node;
  1160. }
  1161. return GetRealOpNode(tuple_inputs[IntToSize(index + 1)]);
  1162. }
  1163. return GetRealOpNode(node_inputs[1]);
  1164. }
  1165. // depend apply inputs: depend,output,depended_node
  1166. if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  1167. auto depend_inputs = node->cast<CNodePtr>()->inputs();
  1168. if (depend_inputs.size() != 3) { // "Depend" primitive have 3 inputs
  1169. MS_LOG(ERROR) << "depend input items not correct";
  1170. error_ = FAILED;
  1171. return node;
  1172. }
  1173. return GetRealOpNode(depend_inputs[1]);
  1174. }
  1175. return node;
  1176. }
  1177. // convert the anf node to corresponding operator list
  1178. std::vector<OperatorPtr> DfGraphConvertor::ConvertDependNode(const AnfNodePtr node) {
  1179. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1180. std::vector<OperatorPtr> op_lists;
  1181. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1182. for (size_t index = 1; index < node_inputs.size(); index++) {
  1183. auto op = Convert(GetRealOpNode(node_inputs[index]));
  1184. if (op == nullptr) {
  1185. MS_LOG(ERROR) << "Convert control depend node to operator failed";
  1186. error_ = FAILED;
  1187. return std::vector<OperatorPtr>({});
  1188. }
  1189. op_lists.push_back(op);
  1190. }
  1191. return op_lists;
  1192. }
  1193. auto op = Convert(GetRealOpNode(node));
  1194. if (op == nullptr) {
  1195. MS_LOG(ERROR) << "Convert control depend node to operator failed";
  1196. error_ = FAILED;
  1197. return std::vector<OperatorPtr>({});
  1198. }
  1199. return std::vector<OperatorPtr>({op});
  1200. }
  1201. // get the anf node list for depend
  1202. std::vector<AnfNodePtr> DfGraphConvertor::GetDependNodes(const AnfNodePtr &node) {
  1203. std::vector<AnfNodePtr> nodes;
  1204. // for make tuple, should control depend on the tuple items
  1205. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1206. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1207. for (size_t index = 1; index < node_inputs.size(); index++) {
  1208. nodes.push_back(GetRealOpNode(node_inputs[index]));
  1209. }
  1210. return nodes;
  1211. }
  1212. // for parameter ,find the apply that used the parameter as the control depended node
  1213. if (node->isa<Parameter>()) {
  1214. auto uses = node->func_graph()->manager()->node_users()[node];
  1215. for (auto &use : uses) {
  1216. auto use_node = use.first;
  1217. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend))) {
  1218. nodes.push_back(GetRealOpNode(use_node));
  1219. }
  1220. }
  1221. return nodes;
  1222. }
  1223. nodes.push_back(GetRealOpNode(node));
  1224. return nodes;
  1225. }
  1226. void DfGraphConvertor::DrawControlDepend(const AnfNodePtr &src_node, const AnfNodePtr &dest_node) {
  1227. #ifdef DRAW_GE_GRAPH
  1228. auto src_depend_nodes = GetDependNodes(src_node);
  1229. auto dst_depend_nodes = GetDependNodes(dest_node);
  1230. if (src_depend_nodes.size() == 1 && dst_depend_nodes.size() > 1) {
  1231. for (auto &item : dst_depend_nodes) {
  1232. compute_sout_ << op_draw_name_[src_depend_nodes[0].get()] << " -> " << op_draw_name_[item.get()]
  1233. << "[style=\"dotted\"]" << endl;
  1234. }
  1235. } else if (src_depend_nodes.size() > 1 && dst_depend_nodes.size() == 1) {
  1236. for (auto &item : src_depend_nodes) {
  1237. compute_sout_ << op_draw_name_[item.get()] << " -> " << op_draw_name_[dst_depend_nodes[0].get()]
  1238. << "[style=\"dotted\"]" << endl;
  1239. }
  1240. } else if (src_depend_nodes.size() == 1 && dst_depend_nodes.size() == 1) {
  1241. compute_sout_ << op_draw_name_[src_depend_nodes[0].get()] << " -> " << op_draw_name_[dst_depend_nodes[0].get()]
  1242. << "[style=\"dotted\"]" << endl;
  1243. }
  1244. #endif
  1245. }
  1246. void DfGraphConvertor::GetDependOnParameterUse(const CNodePtr &node, const AnfNodePtr &src_node,
  1247. const AnfNodePtr &dest_node,
  1248. const std::shared_ptr<std::vector<OperatorPtr>> &src_ops_list,
  1249. const std::shared_ptr<std::vector<OperatorPtr>> &dst_ops_list) {
  1250. if (src_node->isa<Parameter>()) {
  1251. auto uses = node->func_graph()->manager()->node_users()[src_node];
  1252. for (auto &use : uses) {
  1253. auto use_node = use.first;
  1254. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend)) &&
  1255. (!IsPrimitiveCNode(use_node, prim::kPrimMakeTuple))) {
  1256. auto converted_list = ConvertDependNode(use_node);
  1257. src_ops_list->insert(src_ops_list->end(), converted_list.begin(), converted_list.end());
  1258. }
  1259. }
  1260. }
  1261. if (dest_node->isa<Parameter>()) {
  1262. auto uses = node->func_graph()->manager()->node_users()[dest_node];
  1263. for (auto &use : uses) {
  1264. auto use_node = use.first;
  1265. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend)) &&
  1266. (!IsPrimitiveCNode(use_node, prim::kPrimMakeTuple))) {
  1267. auto converted_list = ConvertDependNode(use_node);
  1268. dst_ops_list->insert(dst_ops_list->end(), converted_list.begin(), converted_list.end());
  1269. }
  1270. }
  1271. }
  1272. }
  1273. bool DfGraphConvertor::GetControlDependList(const CNodePtr &node,
  1274. const std::shared_ptr<std::vector<OperatorPtr>> &src_ops_list,
  1275. const std::shared_ptr<std::vector<OperatorPtr>> &dst_ops_list) {
  1276. const int CONTROL_DEPEND_INDEX = 0;
  1277. const int SRC_NODE_INDEX = 1;
  1278. const int DEST_NODE_INDEX = 2;
  1279. const int DEPEND_MODE_NORMAL_USE = 0;
  1280. const int DEPEND_MODE_ON_PARAMETER_USE = 1;
  1281. auto node_inputs = node->inputs();
  1282. if (node_inputs.size() <= DEST_NODE_INDEX) {
  1283. MS_LOG(WARNING) << "Control depend node input size error";
  1284. return false;
  1285. }
  1286. auto src_node = node_inputs[SRC_NODE_INDEX];
  1287. auto dest_node = node_inputs[DEST_NODE_INDEX];
  1288. if ((src_node == nullptr) || (dest_node == nullptr)) {
  1289. MS_LOG(ERROR) << "Control depend node miss src or dest node";
  1290. error_ = FAILED;
  1291. return false;
  1292. }
  1293. AnfNodePtr fn = node_inputs[CONTROL_DEPEND_INDEX];
  1294. PrimitivePtr prim_ptr = GetValueNode<PrimitivePtr>(fn);
  1295. ValuePtr mode_ptr = prim_ptr->GetAttr("depend_mode");
  1296. int depend_mode = DEPEND_MODE_NORMAL_USE;
  1297. if (mode_ptr != nullptr) {
  1298. auto mode_int = mode_ptr->cast<Int64ImmPtr>();
  1299. MS_EXCEPTION_IF_NULL(mode_int);
  1300. depend_mode = mode_int->value();
  1301. MS_LOG(DEBUG) << "depend_mode = " << depend_mode;
  1302. }
  1303. if (depend_mode == DEPEND_MODE_ON_PARAMETER_USE) {
  1304. GetDependOnParameterUse(node, src_node, dest_node, src_ops_list, dst_ops_list);
  1305. }
  1306. if (src_node->isa<CNode>()) {
  1307. auto converted_list = ConvertDependNode(src_node);
  1308. src_ops_list->insert(src_ops_list->end(), converted_list.begin(), converted_list.end());
  1309. }
  1310. if (dest_node->isa<CNode>()) {
  1311. auto converted_list = ConvertDependNode(dest_node);
  1312. dst_ops_list->insert(dst_ops_list->end(), converted_list.begin(), converted_list.end());
  1313. }
  1314. if (src_ops_list->empty() || dst_ops_list->empty()) {
  1315. MS_LOG(DEBUG) << "Control depend node's src or dest node is not a CNode, ignore it";
  1316. error_ = SUCCESS;
  1317. }
  1318. return true;
  1319. }
  1320. void DfGraphConvertor::ConvertControlDependNode(const CNodePtr node) {
  1321. const int SRC_NODE_INDEX = 1;
  1322. const int DEST_NODE_INDEX = 2;
  1323. if (control_depend_cache_.find(node.get()) != control_depend_cache_.end()) {
  1324. return;
  1325. }
  1326. auto node_inputs = node->inputs();
  1327. if (node_inputs.size() <= DEST_NODE_INDEX) {
  1328. MS_LOG(WARNING) << "Control depend node input size error";
  1329. return;
  1330. }
  1331. auto src_node = node_inputs[SRC_NODE_INDEX];
  1332. auto dest_node = node_inputs[DEST_NODE_INDEX];
  1333. if ((src_node == nullptr) || (dest_node == nullptr)) {
  1334. MS_LOG(ERROR) << "Control depend node miss src or dest node";
  1335. error_ = FAILED;
  1336. return;
  1337. }
  1338. std::shared_ptr<std::vector<OperatorPtr>> src_ops_list = std::make_shared<std::vector<OperatorPtr>>();
  1339. std::shared_ptr<std::vector<OperatorPtr>> dst_ops_list = std::make_shared<std::vector<OperatorPtr>>();
  1340. if (!GetControlDependList(node, src_ops_list, dst_ops_list)) {
  1341. MS_LOG(ERROR) << "Get depend list failed";
  1342. error_ = FAILED;
  1343. return;
  1344. }
  1345. std::vector<ControlEdge> control_edges;
  1346. if (src_ops_list->size() == 1 && dst_ops_list->size() > 1) {
  1347. (void)std::transform(dst_ops_list->begin(), dst_ops_list->end(), std::back_inserter(control_edges),
  1348. [src_ops_list](const OperatorPtr &op) -> ControlEdge {
  1349. return {(*src_ops_list)[0], op};
  1350. });
  1351. } else if (src_ops_list->size() > 1 && dst_ops_list->size() == 1) {
  1352. (void)std::transform(src_ops_list->begin(), src_ops_list->end(), std::back_inserter(control_edges),
  1353. [dst_ops_list](const OperatorPtr &op) -> ControlEdge {
  1354. return {op, (*dst_ops_list)[0]};
  1355. });
  1356. } else if (src_ops_list->size() == 1 && dst_ops_list->size() == 1) {
  1357. control_edges.push_back({(*src_ops_list)[0], (*dst_ops_list)[0]});
  1358. } else if (src_ops_list->empty() || dst_ops_list->empty()) {
  1359. MS_LOG(DEBUG) << "Depend list of src or dst is empty, ignore it";
  1360. } else {
  1361. MS_LOG(ERROR) << "Convert control depend node to operator failed, depend src:" << src_ops_list->size()
  1362. << " -> dst:" << dst_ops_list->size();
  1363. error_ = FAILED;
  1364. return;
  1365. }
  1366. control_depend_cache_[node.get()] = control_edges;
  1367. #ifdef DRAW_GE_GRAPH
  1368. DrawControlDepend(src_node, dest_node);
  1369. #endif
  1370. }
  1371. bool DfGraphConvertor::CheckCNode(const std::string &name, const CNodePtr node) {
  1372. // ignore apply node of return
  1373. if (name == "return" || name == "Depend") {
  1374. return false;
  1375. }
  1376. if (name == "" && GetCNodeFuncName(node) == "switch_layer") {
  1377. return false;
  1378. }
  1379. if (name == "Partial") {
  1380. return false;
  1381. }
  1382. // make_tuple is used for a dynamic_input, convert it to a vector of OutHandlers
  1383. if (name == "make_tuple") {
  1384. ConvertMakeTuple(node);
  1385. return false;
  1386. }
  1387. // As for nodes with multi outputs, convert tuple_getitem to OutHandle
  1388. if (name == "tuple_getitem") {
  1389. ConvertTupleGetItem(node);
  1390. return false;
  1391. }
  1392. if (name == "ControlDepend") {
  1393. ConvertControlDependNode(node);
  1394. return false;
  1395. }
  1396. return true;
  1397. }
  1398. OperatorPtr DfGraphConvertor::ConvertCNode(const CNodePtr node) {
  1399. std::string name = GetCNodeTargetFuncName(node);
  1400. if (!CheckCNode(name, node)) {
  1401. return nullptr;
  1402. }
  1403. // get corresponding OpAdapter
  1404. OpAdapterPtr adpt = FindAdapter(node, training_);
  1405. if (adpt == nullptr) {
  1406. error_ = NOT_FOUND;
  1407. return nullptr;
  1408. }
  1409. // get operator
  1410. OperatorPtr op = nullptr;
  1411. auto it_op = op_cache_.find(node.get());
  1412. if (it_op != op_cache_.end()) {
  1413. op = it_op->second;
  1414. } else {
  1415. op = adpt->generate(node);
  1416. }
  1417. // set attribute for primitive
  1418. (void)adpt->setAttr(op, node);
  1419. // add into cache
  1420. (void)op_cache_.insert(std::make_pair(node.get(), op));
  1421. DrawCNode(node, adpt);
  1422. return op_cache_[node.get()];
  1423. }
  1424. OperatorPtr DfGraphConvertor::ConvertParameter(const AnfNodePtr node) {
  1425. // convert Parameter in ANF to variable in DataFlow
  1426. auto op = FindAdapter(node, training_)->generate(node);
  1427. op_cache_[node.get()] = op;
  1428. // build index for parameter using name
  1429. std::string name = std::static_pointer_cast<Parameter>(node)->name();
  1430. params_[name] = node;
  1431. std::ostringstream ss;
  1432. ss << "op" << node.get();
  1433. op_draw_name_[node.get()] = ss.str();
  1434. compute_sout_ << ss.str() << "[shape=octagon, label=\"" << name << "\"]" << endl;
  1435. return op_cache_[node.get()];
  1436. }
  1437. Status DfGraphConvertor::TryConvertValueNodeToMultiConst(const ValueNodePtr node) {
  1438. MS_EXCEPTION_IF_NULL(node);
  1439. ValuePtr value = node->value();
  1440. MS_EXCEPTION_IF_NULL(value);
  1441. if (!value->isa<ValueList>() && !value->isa<ValueTuple>()) {
  1442. return FAILED;
  1443. }
  1444. auto vec = value->isa<ValueTuple>() ? value->cast<ValueTuplePtr>()->value() : value->cast<ValueListPtr>()->value();
  1445. if (vec.empty()) {
  1446. return FAILED;
  1447. }
  1448. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  1449. for (size_t i = 0; i < vec.size(); i++) {
  1450. MS_EXCEPTION_IF_NULL(vec[i]);
  1451. if (vec[i]->isa<MeTensor>()) {
  1452. GeTensorPtr ge_tensor = transform::TransformUtil::ConvertTensor(vec[i]->cast<MeTensorPtr>(), kOpFormat_NCHW);
  1453. auto const_op = std::make_shared<Constant>(node->fullname_with_scope() + "/const/inputs/" + std::to_string(i));
  1454. (void)const_op->set_attr_value(*ge_tensor);
  1455. (void)const_op->update_output_desc_y(ge_tensor->GetTensorDesc());
  1456. tuple_items->emplace_back(OutHandler(const_op, ""));
  1457. } else {
  1458. return FAILED;
  1459. }
  1460. }
  1461. if (tuple_items->empty()) {
  1462. return FAILED;
  1463. }
  1464. tuple_out_handle_cache_[node.get()] = tuple_items;
  1465. return SUCCESS;
  1466. }
  1467. OperatorPtr DfGraphConvertor::ConvertValueNode(const ValueNodePtr node) {
  1468. // convert valuenode in ANF to Const in DataFlow
  1469. // find paramerte referenced by SymbolicKeyInstance of valuenode
  1470. std::ostringstream ss;
  1471. ss << "op" << node.get();
  1472. op_draw_name_[node.get()] = ss.str();
  1473. compute_sout_ << ss.str() << "[label= \"" << node->value()->ToString() << "\" shape=ellipse]" << endl;
  1474. if (TryConvertValueNodeToMultiConst(node) == SUCCESS) {
  1475. MS_LOG(INFO) << "Convert value node to multi Constant OP success";
  1476. return nullptr;
  1477. }
  1478. OpAdapterPtr adpt = FindAdapter(node, training_);
  1479. if (adpt == nullptr) {
  1480. error_ = NOT_FOUND;
  1481. return nullptr;
  1482. }
  1483. auto op = adpt->generate(node);
  1484. // set const's attrs
  1485. if (adpt->setAttr(op, "value", node->value()) != 0) {
  1486. MS_LOG(WARNING) << "set attr value for const failed";
  1487. }
  1488. #if (defined ENABLE_GE)
  1489. auto const_op = std::static_pointer_cast<Constant>(op);
  1490. if (const_op == nullptr) {
  1491. MS_LOG(ERROR) << "Get Constant operator failed";
  1492. return nullptr;
  1493. }
  1494. auto ge_tensor = const_op->get_attr_value();
  1495. auto ge_desc = ge_tensor.GetTensorDesc();
  1496. (void)const_op->update_output_desc_y(ge_desc);
  1497. #endif
  1498. op_cache_[node.get()] = op;
  1499. return op_cache_[node.get()];
  1500. }
  1501. void DfGraphConvertor::DrawCNode(const CNodePtr node, const OpAdapterPtr adpt) {
  1502. if (nullptr == adpt || nullptr == node) {
  1503. MS_LOG(ERROR) << "Failed to draw apply node as adpt or node is nullptr!";
  1504. return;
  1505. }
  1506. std::ostringstream ss;
  1507. ss << "op" << node.get();
  1508. op_draw_name_[node.get()] = ss.str();
  1509. compute_sout_ << ss.str() << "[label=<";
  1510. compute_sout_ << "<table border='1' cellborder='1'>" << endl;
  1511. auto input_map = adpt->getInputMap();
  1512. auto dyn_input_map = adpt->getDynInputMap();
  1513. if (input_map.size() + dyn_input_map.size() > 0) {
  1514. compute_sout_ << "<tr>";
  1515. for (auto &it : input_map) {
  1516. compute_sout_ << "<td port='" << it.first << "'>" << it.second.name << "</td>";
  1517. }
  1518. for (auto &it : dyn_input_map) {
  1519. compute_sout_ << "<td port='" << it.first << "'>" << it.second.name << "</td>";
  1520. }
  1521. compute_sout_ << "</tr>" << endl;
  1522. }
  1523. compute_sout_ << "<tr><td colspan=\"" << (input_map.size() + dyn_input_map.size()) << "\">\"" << node->ToString()
  1524. << ":" << GetCNodeTargetFuncName(node) << "\"</td></tr>" << endl;
  1525. // print attrs' values
  1526. auto atts = adpt->GetAttrsFromDrawGraph();
  1527. for (auto &it : atts) {
  1528. compute_sout_ << "<tr><td colspan=\"" << (input_map.size() + dyn_input_map.size()) << "\">\"" << it
  1529. << "\"</td></tr>";
  1530. }
  1531. adpt->clearAttrVect();
  1532. compute_sout_ << "</table>> shape=plaintext]" << endl;
  1533. }
  1534. void DfGraphConvertor::RegisterAdapter(const std::string &name, OpAdapterPtr adpt) {
  1535. OpAdapterMap::get()[name] = std::make_shared<OpAdapterDesc>(adpt);
  1536. }
  1537. void DfGraphConvertor::RegisterAdapter(const std::string &name, OpAdapterPtr train_adpt, OpAdapterPtr infer_adpt) {
  1538. OpAdapterMap::get()[name] = std::make_shared<OpAdapterDesc>(train_adpt, infer_adpt);
  1539. }
  1540. } // namespace transform
  1541. } // namespace mindspore