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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709
  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 Parameter node
  534. TraceOutputFromParameter(anf_out);
  535. // then trace cnode
  536. if (!node->isa<CNode>()) {
  537. return;
  538. }
  539. // trace tuple_getitem
  540. while (anf_out->isa<CNode>() && IsPrimitiveCNode(anf_out, prim::kPrimTupleGetItem)) {
  541. pre_node = anf_out;
  542. anf_out = anf_out->cast<CNodePtr>()->input(1);
  543. }
  544. // trace every element of make_tuple
  545. auto c = anf_out->cast<CNodePtr>();
  546. std::string name = "";
  547. if (anf_out->isa<CNode>()) {
  548. name = GetCNodeTargetFuncName(c);
  549. }
  550. if (name == "make_tuple") {
  551. for (unsigned int i = 1; i < c->inputs().size(); i++) {
  552. TraceOutput(c->input(i));
  553. }
  554. } else if (name == "Depend") {
  555. if (c->inputs().size() < 3) { // "Depend" primitive have 3 inputs
  556. MS_LOG(EXCEPTION) << "length of inputs is " << c->inputs().size() << ", which is less than 3";
  557. }
  558. TraceOutput(c->input(1));
  559. } else if (name == "tuple_getitem") {
  560. TraceOutputFromTupleGetItem(anf_out);
  561. } else {
  562. // add outputs;
  563. auto op = Convert(anf_out);
  564. std::string index;
  565. if (op != nullptr) {
  566. if ((pre_node != nullptr) && IsPrimitiveCNode(pre_node, prim::kPrimTupleGetItem)) {
  567. auto item = out_handle_cache_.find(pre_node.get());
  568. if (item != out_handle_cache_.end()) {
  569. index = item->second.out;
  570. } else {
  571. MS_LOG(WARNING) << "Can't get operater: " << anf_out->fullname_with_scope() << " 's output item";
  572. }
  573. }
  574. MS_LOG(INFO) << "Add graph output: " << anf_out->fullname_with_scope() << ":" << index;
  575. graph_outputs_.emplace_back(make_pair(*op, index));
  576. }
  577. }
  578. }
  579. void DfGraphConvertor::TraceOutputFromParameter(const AnfNodePtr &anf_out) {
  580. if (anf_out->isa<Parameter>()) {
  581. MS_LOG(INFO) << "Add graph output: " << anf_out->fullname_with_scope();
  582. auto it = out_handle_cache_.find(anf_out.get());
  583. if (it != out_handle_cache_.end()) {
  584. // For dataset graph mode, input parameter is converted to a "iterator_get_next:yn" OutHandler.
  585. OutHandler handle = it->second;
  586. auto op = handle.op;
  587. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType() << ", out_name: " << handle.out;
  588. graph_outputs_.emplace_back(make_pair(*op, handle.out));
  589. } else {
  590. // common parameter case
  591. auto op = Convert(anf_out);
  592. if (op != nullptr) {
  593. MS_LOG(INFO) << "op name: " << op->GetName() << ", op type: " << op->GetOpType();
  594. graph_outputs_.emplace_back(std::make_pair(*op, ""));
  595. }
  596. }
  597. }
  598. }
  599. void SetupDatasetIterGetNextNode(const OperatorPtr &op) {
  600. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  601. DatasetGraphParam param = ConfigManager::GetInstance().dataset_param();
  602. size_t output_num = param.ge_types().size();
  603. MS_LOG(INFO) << "Set iterator_getnext op's output num = " << output_num << ".";
  604. // set iterator_getnext op's output num
  605. shared_ptr<ge::op::GetNext> iter_getnext = std::static_pointer_cast<ge::op::GetNext>(op);
  606. (void)iter_getnext->create_dynamic_output_y(static_cast<unsigned int>(output_num));
  607. for (uint32_t i = 0; i < output_num; i++) {
  608. ge::TensorDesc desc(GeShape(param.shapes()[i]), ge::FORMAT_NCHW, (ge::DataType)param.ge_types()[i]);
  609. // we don't SetRealDimCnt here since GE do not use this output's real-dim
  610. (void)iter_getnext->update_dynamic_output_desc_y((i), desc);
  611. }
  612. }
  613. return;
  614. }
  615. void DfGraphConvertor::SetSubgraph(AnfNodePtr node) {
  616. if (!node->isa<CNode>()) {
  617. return;
  618. }
  619. auto cnode = node->cast<CNodePtr>();
  620. if (!IsCaseNode(cnode)) {
  621. return;
  622. }
  623. std::vector<AnfNodePtr> case_inputs;
  624. for (size_t i = 1; i < cnode->inputs().size(); i++) {
  625. case_inputs.emplace_back(cnode->input(i));
  626. }
  627. std::shared_ptr<std::vector<DfGraph>> branches = std::make_shared<std::vector<DfGraph>>();
  628. auto bnode = cnode->input(0)->cast<CNodePtr>()->input(2)->cast<CNodePtr>();
  629. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  630. auto branch_node = bnode->input(i)->cast<CNodePtr>();
  631. for (size_t j = 2; j < branch_node->inputs().size(); j++) {
  632. if (std::find(case_inputs.begin(), case_inputs.end(), branch_node->input(j)) == case_inputs.end()) {
  633. case_inputs.emplace_back(branch_node->input(j));
  634. }
  635. }
  636. }
  637. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  638. ProcessSubgraph(bnode->input(i), case_inputs);
  639. }
  640. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  641. branches->emplace_back(branches_map_[bnode->input(i).get()]);
  642. }
  643. if (op_cache_.find(node.get()) == op_cache_.end()) {
  644. return;
  645. }
  646. OpAdapterPtr adpt = FindAdapter(node, training_);
  647. if (nullptr == adpt) {
  648. MS_LOG(DEBUG) << "Not found adapter";
  649. return;
  650. }
  651. OperatorPtr op = Convert(node);
  652. adpt->setSubgraph(op, 0, branches);
  653. return;
  654. }
  655. void DfGraphConvertor::GetCaseNodeInput(const CNodePtr node, const CNodePtr input_node) {
  656. std::vector<AnfNodePtr> case_inputs;
  657. for (size_t i = 1; i < node->inputs().size(); i++) {
  658. case_inputs.emplace_back(node->input(i));
  659. }
  660. std::shared_ptr<std::vector<DfGraph>> branches = std::make_shared<std::vector<DfGraph>>();
  661. auto bnode = input_node->input(2)->cast<CNodePtr>();
  662. for (size_t i = 1; i < bnode->inputs().size(); i++) {
  663. auto branch_node = bnode->input(i)->cast<CNodePtr>();
  664. for (size_t j = 2; j < branch_node->inputs().size(); j++) {
  665. if (std::find(case_inputs.begin(), case_inputs.end(), branch_node->input(j)) == case_inputs.end()) {
  666. case_inputs.emplace_back(branch_node->input(j));
  667. }
  668. }
  669. }
  670. const size_t case_index = 1;
  671. const size_t make_tuple_index = 2;
  672. AnfNodePtr case_index_iter = input_node->input(case_index);
  673. AnfNodePtr make_tuple_iter = input_node->input(make_tuple_index);
  674. auto make_tuple_node = make_tuple_iter->cast<CNodePtr>();
  675. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  676. for (size_t i = 0; i < case_inputs.size(); i++) {
  677. auto item = case_inputs[i];
  678. auto op = Convert(item);
  679. if (op != nullptr) {
  680. tuple_items->emplace_back(OutHandler(op, ""));
  681. } else if (out_handle_cache_.find(item.get()) != out_handle_cache_.end()) {
  682. tuple_items->push_back(out_handle_cache_[item.get()]);
  683. } else {
  684. MS_LOG(WARNING) << "This anf node is not supported as a case input: " << item->ToString();
  685. continue;
  686. }
  687. }
  688. tuple_out_handle_cache_[make_tuple_node.get()] = tuple_items;
  689. std::shared_ptr<std::vector<AnfNodePtr>> case_input_items = std::make_shared<std::vector<AnfNodePtr>>();
  690. case_input_items->emplace_back(case_index_iter);
  691. case_input_items->emplace_back(make_tuple_iter);
  692. case_input_handle_cache_[node.get()] = case_input_items;
  693. }
  694. DfGraphConvertor &DfGraphConvertor::BuildGraph() {
  695. SetupDatasetIterGetNextNode(dataset_iter_getnext_);
  696. if (error_ != 0) {
  697. return *this;
  698. }
  699. // Case node set input.
  700. std::vector<AnfNodePtr> nodes = ::mindspore::TopoSort(anf_graph_->get_return());
  701. for (auto &it : nodes) {
  702. if (it->isa<CNode>() && IsCaseNode(it->cast<CNodePtr>())) {
  703. auto node = it->cast<CNodePtr>();
  704. auto input_node = node->input(0)->cast<CNodePtr>();
  705. GetCaseNodeInput(node, input_node);
  706. }
  707. }
  708. // update tuple_out_handle_cache_
  709. for (auto it : tuple_out_handle_cache_) {
  710. std::size_t len = it.second->size();
  711. for (std::size_t i = 0; i < len; i++) {
  712. OutHandler handle = (*it.second)[i];
  713. if (handle.op) {
  714. string name = handle.op->GetName();
  715. if (vars_.count(name)) {
  716. OperatorPtr new_op = vars_[name];
  717. if (new_op != nullptr) {
  718. MS_LOG(INFO) << "update tuple_out_handle_cache_ " << name;
  719. (*it.second)[i] = OutHandler(new_op, handle.out);
  720. }
  721. }
  722. }
  723. }
  724. }
  725. // set up dependices
  726. MS_LOG(DEBUG) << "set up dependices";
  727. nodes = ::mindspore::TopoSort(anf_graph_->get_return());
  728. for (auto &it : nodes) {
  729. SetNodeInput(it);
  730. SetOpControlInput(it);
  731. SetSubgraph(it);
  732. UpdateOpDesc(it);
  733. }
  734. if (error_ == 0) {
  735. df_graph_ = make_shared<DfGraph>(anf_graph_->ToString());
  736. } else {
  737. return *this;
  738. }
  739. // set graph input according to the order from anf graph
  740. std::vector<Operator> inputs;
  741. if (ConfigManager::GetInstance().dataset_mode() == DS_SINK_MODE) {
  742. inputs.push_back(*dataset_iter_getnext_);
  743. } else {
  744. auto params = anf_graph_->parameters();
  745. if (use_inputs_) {
  746. params = inputs_;
  747. auto anf_params = anf_graph_->parameters();
  748. for (size_t i = 0; i < params.size(); i++) {
  749. for (size_t j = 0; j < anf_params.size(); j++) {
  750. if (params[i]->ToString() == anf_params[j]->ToString()) {
  751. params[i] = anf_params[j];
  752. }
  753. }
  754. }
  755. }
  756. int index = 0;
  757. for (auto &it : params) {
  758. auto name = std::static_pointer_cast<Parameter>(it)->name();
  759. // the parameters which has not been converted to var
  760. if (vars_.find(name) == vars_.end()) {
  761. auto op = Convert(it);
  762. MS_EXCEPTION_IF_NULL(op);
  763. MS_LOG(INFO) << "add not var input " << it->ToString() << ", index " << index;
  764. if (op == nullptr) {
  765. MS_LOG(ERROR) << "Convert graph failed!";
  766. return *this;
  767. }
  768. UpdateDataOpDesc(it, op);
  769. MS_LOG(INFO) << "add input " << it->ToString() << ", index " << index;
  770. (void)std::static_pointer_cast<Data>(op)->set_attr_index(index++);
  771. inputs.push_back(*op);
  772. } else if (vars_[name] != nullptr) {
  773. MS_LOG(INFO) << "add var input " << it->ToString();
  774. auto op = Convert(it);
  775. MS_EXCEPTION_IF_NULL(op);
  776. inputs.push_back(*op);
  777. }
  778. }
  779. }
  780. // Add const nodes as graph input for some operator work with constant
  781. std::transform(graph_const_inputs_.begin(), graph_const_inputs_.end(), std::back_inserter(inputs),
  782. [](OperatorPtr x) { return *x; });
  783. MS_LOG(INFO) << "set graph input num: " << inputs.size();
  784. (void)df_graph_->SetInputs(inputs);
  785. // set graph output
  786. // set the value of finale return apply node as the output of dataflow graph
  787. MS_LOG(DEBUG) << "set output";
  788. graph_outputs_.clear();
  789. TraceOutput(anf_graph_->get_return()->input(1));
  790. MS_LOG(INFO) << "set graph output num: " << graph_outputs_.size();
  791. (void)df_graph_->SetOutputs(graph_outputs_);
  792. compute_sout_ << "}" << endl;
  793. // For the graph(e.g. eval_subgraph) whose IterNum is 1, donot set NeedIteration flag.
  794. if (ConfigManager::GetInstance().iter_num() > 1) {
  795. df_graph_->SetNeedIteration(true);
  796. }
  797. return *this;
  798. }
  799. void DfGraphConvertor::UpdateDataOpDesc(const AnfNodePtr &it, const OperatorPtr &op) const {
  800. auto node = std::static_pointer_cast<AnfNode>(it);
  801. if (node == nullptr) {
  802. MS_LOG(ERROR) << "Update data op descriptor failed! Invalid node.";
  803. return;
  804. }
  805. auto normal_shape_ptr = dyn_cast<abstract::Shape>(node->Shape());
  806. vector<int> shape;
  807. if (normal_shape_ptr == nullptr) {
  808. MS_LOG(INFO) << "Invalid shape to update data op descriptor.";
  809. return;
  810. }
  811. shape = normal_shape_ptr->shape();
  812. if (node->Type() == nullptr) {
  813. MS_LOG(INFO) << "Invalid type to update data op descriptor.";
  814. return;
  815. }
  816. TypeId me_type = node->Type()->type_id();
  817. if (kObjectTypeTensorType == me_type) {
  818. me_type = dyn_cast<TensorType>(node->Type())->element()->type_id();
  819. }
  820. std::ostringstream buf;
  821. buf << "[" << shape << "]";
  822. MS_LOG(INFO) << "input shape is " << buf.str() << ", type is " << me_type;
  823. auto desc = TransformUtil::GetGeTensorDesc(shape, me_type, "NCHW");
  824. if (desc == nullptr) {
  825. MS_LOG(ERROR) << "Update data op descriptor failed! TensorDesc is null.";
  826. } else {
  827. (void)std::static_pointer_cast<Data>(op)->update_input_desc_x(*desc);
  828. (void)std::static_pointer_cast<Data>(op)->update_output_desc_y(*desc);
  829. }
  830. }
  831. DfGraphPtr DfGraphConvertor::GetComputeGraph() { return df_graph_; }
  832. DfGraphPtr DfGraphConvertor::GetInitGraph() { return init_graph_; }
  833. DfGraphPtr DfGraphConvertor::GetSaveCheckpointGraph() { return save_ckp_graph_; }
  834. DfGraphPtr DfGraphConvertor::GetBroadcastGraph() { return broadcast_graph_; }
  835. void DfGraphConvertor::SetOpControlInput(const AnfNodePtr node) {
  836. if (control_depend_cache_.find(node.get()) == control_depend_cache_.end()) {
  837. return;
  838. }
  839. std::vector<ControlEdge> control_edges = control_depend_cache_[node.get()];
  840. if ((control_edges.empty())) {
  841. MS_LOG(ERROR) << "Get control depend node's src or dest operator failed";
  842. return;
  843. }
  844. for (auto &item : control_edges) {
  845. (void)item.dest_op->AddControlInput(*item.src_op);
  846. }
  847. }
  848. const std::vector<std::string> trans_var_list = {string(kNameAssign), string(kNameAssignAdd), string(kNameAssignSub)};
  849. void DfGraphConvertor::SetOpInput(const OpAdapterPtr &adpt, const CNodePtr &node) {
  850. OperatorPtr src = Convert(node);
  851. int case_flag = 0;
  852. auto &inputs = node->inputs();
  853. size_t input_size = inputs.size();
  854. if (case_input_handle_cache_.find(node.get()) != case_input_handle_cache_.end()) {
  855. case_flag = 1;
  856. input_size = case_input_handle_cache_[node.get()]->size() + 1;
  857. }
  858. for (size_t i = 1; i < input_size; i++) {
  859. AnfNodePtr pred = nullptr;
  860. if (case_flag != 0) {
  861. pred = case_input_handle_cache_[node.get()]->at(i - 1);
  862. } else {
  863. pred = inputs[i];
  864. }
  865. while (pred->isa<CNode>() && GetCNodeTargetFuncName(pred->cast<CNodePtr>()) == "Depend") {
  866. pred = pred->cast<CNodePtr>()->input(1);
  867. }
  868. // skip the None input
  869. if (IsValueNode<None>(pred)) {
  870. continue;
  871. }
  872. // transform "Const" op to "Variable" op when the next node is "Assign" op.
  873. std::string c_name = GetCNodeTargetFuncName(node);
  874. auto pos = std::find(trans_var_list.begin(), trans_var_list.end(), c_name);
  875. if (!training_ && pos != trans_var_list.end() && pred->isa<Parameter>()) {
  876. std::string name = std::static_pointer_cast<Parameter>(pred)->name();
  877. auto op_itor = op_cache_.find(pred.get());
  878. if (op_itor == op_cache_.end()) {
  879. MS_LOG(EXCEPTION) << "Can not find op for node " << pred->ToString() << ".";
  880. }
  881. if (op_itor->second != nullptr &&
  882. (op_itor->second->GetOpType() == "Constant" || op_itor->second->GetOpType() == "Const") &&
  883. vars_.find(name) != vars_.end()) {
  884. auto variable = std::make_shared<Variable>(name);
  885. auto desc = vars_[name]->GetOutputDesc("y");
  886. (void)variable->update_output_desc_y(desc);
  887. MS_LOG(DEBUG) << "Trans to variable, var = " << variable->GetName() << ".";
  888. op_itor->second = variable; // replace parameter with variable
  889. vars_[name] = variable;
  890. }
  891. }
  892. // find in out_hadnle_cache_ first
  893. auto it = out_handle_cache_.find(pred.get());
  894. if (it != out_handle_cache_.end()) {
  895. int ret = adpt->setInput(src, SizeToInt(i), it->second);
  896. if (ret == 0) {
  897. if (pred->isa<CNode>() && GetCNodeTargetFuncName(pred->cast<CNodePtr>()) == "tuple_getitem") {
  898. compute_sout_ << op_draw_name_[pred->cast<CNodePtr>()->input(1).get()] << " -> " << op_draw_name_[node.get()]
  899. << ":" << i << endl;
  900. } else if (pred->isa<Parameter>()) {
  901. compute_sout_ << op_draw_name_[pred.get()] << " -> " << op_draw_name_[node.get()] << ":" << i << endl;
  902. } else {
  903. // don't draw anything.
  904. MS_LOG(INFO) << "DRAW_GE_GRAPH: Shouldn't have this case.";
  905. }
  906. AddGraphConstInput(it->second.op);
  907. }
  908. } else if (tuple_out_handle_cache_.find(pred.get()) != tuple_out_handle_cache_.end()) {
  909. std::shared_ptr<std::vector<OutHandler>> handler_vec = tuple_out_handle_cache_[pred.get()];
  910. int ret = adpt->setInput(src, SizeToInt(i), handler_vec);
  911. if ((ret == 0) && pred->isa<CNode>() && (pred->cast<CNodePtr>()->inputs().size() == handler_vec->size() + 1)) {
  912. for (unsigned int j = 0; j < handler_vec->size(); j++) {
  913. compute_sout_ << op_draw_name_[pred->cast<CNodePtr>()->input(j + 1).get()] << " -> "
  914. << op_draw_name_[node.get()] << ":" << i << endl;
  915. AddGraphConstInput(handler_vec->at(j).op);
  916. }
  917. } else {
  918. MS_LOG(WARNING) << "Convert tuple node setInput failed : " << node->ToString();
  919. }
  920. } else {
  921. auto op = Convert(pred);
  922. int ret = adpt->setInput(src, SizeToInt(i), op);
  923. if (ret == 0) {
  924. compute_sout_ << op_draw_name_[pred.get()] << " -> " << op_draw_name_[node.get()] << ":" << i << endl;
  925. AddGraphConstInput(op);
  926. }
  927. }
  928. }
  929. }
  930. void DfGraphConvertor::AddGraphConstInput(const OperatorPtr &op) {
  931. if (op->GetOpType() == "Constant") {
  932. graph_const_inputs_.push_back(op);
  933. }
  934. }
  935. void DfGraphConvertor::SetNodeInput(const AnfNodePtr node) {
  936. if (!node->isa<CNode>()) {
  937. return;
  938. }
  939. if (op_cache_.find(node.get()) == op_cache_.end()) {
  940. return;
  941. }
  942. auto cnode = node->cast<CNodePtr>();
  943. OpAdapterPtr adpt = FindAdapter(cnode, training_);
  944. if (adpt == nullptr) {
  945. error_ = NOT_FOUND;
  946. return;
  947. }
  948. // get Operator from op_cache_, use adapter to set Inputs
  949. DfGraphConvertor::SetOpInput(adpt, cnode);
  950. }
  951. void DfGraphConvertor::ProcessSubgraph(AnfNodePtr node, const std::vector<AnfNodePtr> &inputs) {
  952. if (!node->isa<CNode>() || GetCNodeFuncName(node->cast<CNodePtr>()) != "Partial") {
  953. return;
  954. }
  955. auto graph_node = node->cast<CNodePtr>()->input(1)->cast<ValueNodePtr>();
  956. FuncGraphPtr anf_graph = graph_node->value()->cast<FuncGraphPtr>();
  957. DfGraphConvertor convertor(anf_graph);
  958. convertor.use_inputs_ = true;
  959. convertor.inputs_ = inputs;
  960. (void)convertor.ConvertAllNode().BuildGraph();
  961. std::string name = graph_node->ToString() + "_ge_graph.dot";
  962. if (MsContext::GetInstance()->get_param<bool>(MS_CTX_SAVE_GRAPHS_FLAG)) {
  963. convertor.DrawComputeGraph(name);
  964. }
  965. branches_map_[node.get()] = *(convertor.df_graph_);
  966. }
  967. // Update GE op's shape and type info
  968. void DfGraphConvertor::UpdateOpDesc(const AnfNodePtr node) {
  969. if (nullptr == node || !node->isa<CNode>()) {
  970. return;
  971. }
  972. if (op_cache_.find(node.get()) == op_cache_.end()) {
  973. return;
  974. }
  975. OpAdapterPtr adpt = FindAdapter(node, training_);
  976. if (adpt == nullptr) {
  977. error_ = NOT_FOUND;
  978. return;
  979. }
  980. // get Operator from op_cache_
  981. OperatorPtr op = Convert(node);
  982. adpt->updateOutputDesc(op, node->Shape(), node->Type(), node);
  983. }
  984. OperatorPtr DfGraphConvertor::Convert(const AnfNodePtr node) {
  985. if (node == nullptr) {
  986. MS_LOG(ERROR) << "node is nullptr";
  987. error_ = NOT_FOUND;
  988. return nullptr;
  989. }
  990. // find in cache
  991. if (op_cache_.count(node.get())) {
  992. return op_cache_[node.get()];
  993. }
  994. // do not convert primitive node
  995. if (IsValueNode<Primitive>(node)) {
  996. return nullptr;
  997. }
  998. // convert a new one
  999. if (node->isa<CNode>()) {
  1000. return ConvertCNode(node->cast<CNodePtr>());
  1001. }
  1002. if (node->isa<Parameter>()) {
  1003. return ConvertParameter(node);
  1004. }
  1005. if (node->isa<ValueNode>()) {
  1006. return ConvertValueNode(node->cast<ValueNodePtr>());
  1007. }
  1008. MS_LOG(ERROR) << "Invalide AnfNode";
  1009. error_ = INVALID_ARGUMENT;
  1010. return nullptr;
  1011. }
  1012. void DfGraphConvertor::ConvertMakeTuple(const CNodePtr node) {
  1013. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  1014. // convert each tuple item to a OutHandler
  1015. for (size_t i = 1; i < node->inputs().size(); i++) {
  1016. AnfNodePtr item = node->input(i);
  1017. OperatorPtr op = Convert(item);
  1018. if (op != nullptr) {
  1019. tuple_items->emplace_back(OutHandler(op, ""));
  1020. } else if (out_handle_cache_.find(item.get()) != out_handle_cache_.end()) {
  1021. tuple_items->push_back(out_handle_cache_[item.get()]);
  1022. } else {
  1023. MS_LOG(WARNING) << "This anf node is not supported as a tuple item : " << item->ToString();
  1024. return;
  1025. }
  1026. }
  1027. MS_LOG(WARNING) << "ConvertMakeTuple: " << node.get() << " " << tuple_items->size();
  1028. tuple_out_handle_cache_[node.get()] = tuple_items;
  1029. }
  1030. AnfNodePtr DfGraphConvertor::TraceTupleGetItem(const CNodePtr &node, unsigned int *index) {
  1031. const int TUPLE_GET_ITEM_INDEX = 2;
  1032. if (node->inputs().size() < 3) { // "tuple_getitem" primitive must have 3 inputs
  1033. MS_LOG(EXCEPTION) << "length of inputs of TupleGetItem is less than 3";
  1034. }
  1035. auto index_node = node->inputs()[TUPLE_GET_ITEM_INDEX];
  1036. if (!index_node->isa<ValueNode>()) {
  1037. error_ = INVALID_ARGUMENT;
  1038. MS_LOG(EXCEPTION) << "can't convert get item with non-constant index";
  1039. }
  1040. *index = IntToUint(GetValue<int>(GetValueNode(index_node)));
  1041. return node->inputs()[1];
  1042. }
  1043. AnfNodePtr DfGraphConvertor::TraceDepend(const CNodePtr &node) {
  1044. auto cnode = node->cast<CNodePtr>();
  1045. if (cnode->inputs().size() < 3) { // "Depend" primitive have 3 inputs
  1046. MS_LOG(EXCEPTION) << "length of inputs of depend is less than 3";
  1047. }
  1048. return cnode->inputs()[1];
  1049. }
  1050. AnfNodePtr DfGraphConvertor::TraceMakeTuple(const CNodePtr &node, unsigned int index) {
  1051. if (index + 1 >= node->inputs().size()) {
  1052. MS_LOG(EXCEPTION) << "length of make_tuple is less than index: " << index;
  1053. }
  1054. return node->inputs()[index + 1];
  1055. }
  1056. OutHandler DfGraphConvertor::GetHandler(const AnfNodePtr &node, const std::stack<unsigned int> &index_stack,
  1057. AnfNode *const draw_index) {
  1058. if (node == nullptr) {
  1059. MS_LOG(ERROR) << "Get nullptr while trace real op";
  1060. return OutHandler(nullptr, "");
  1061. }
  1062. std::ostringstream ss;
  1063. ss << "op" << node.get();
  1064. if (index_stack.empty()) {
  1065. op_draw_name_[draw_index] = ss.str();
  1066. return OutHandler(Convert(node), "");
  1067. } else {
  1068. OpAdapterPtr adpt = FindAdapter(node, training_);
  1069. if (nullptr == adpt) {
  1070. MS_LOG(ERROR) << "Can not get node output as adpt is nullptr!";
  1071. error_ = NOT_FOUND;
  1072. return OutHandler(nullptr, "");
  1073. }
  1074. OperatorPtr op = Convert(node);
  1075. if (op == nullptr) {
  1076. error_ = NOT_FOUND;
  1077. MS_LOG(ERROR) << "Can not convert node for trace real op";
  1078. return OutHandler(nullptr, "");
  1079. }
  1080. op_draw_name_[draw_index] = ss.str();
  1081. return adpt->getOutput(Convert(node), UintToInt(index_stack.top()));
  1082. }
  1083. }
  1084. // get the real operator through maketuple tuple_getitem depend
  1085. OutHandler DfGraphConvertor::TraceRealOp(AnfNodePtr node) {
  1086. bool flag = IsPrimitiveCNode(node, prim::kPrimTupleGetItem) || IsPrimitiveCNode(node, prim::kPrimMakeTuple) ||
  1087. IsPrimitiveCNode(node, prim::kPrimDepend);
  1088. std::stack<unsigned int> index_stack;
  1089. auto draw_index = node.get();
  1090. while (flag) {
  1091. flag = false;
  1092. if (IsPrimitiveCNode(node, prim::kPrimTupleGetItem)) {
  1093. unsigned int index;
  1094. node = TraceTupleGetItem(node->cast<CNodePtr>(), &index);
  1095. index_stack.push(index);
  1096. flag = true;
  1097. } else if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1098. if (index_stack.empty()) {
  1099. MS_LOG(ERROR) << "TraceRealOp find a make_tuple node";
  1100. return OutHandler(nullptr, "");
  1101. } else {
  1102. node = TraceMakeTuple(node->cast<CNodePtr>(), index_stack.top());
  1103. index_stack.pop();
  1104. flag = true;
  1105. }
  1106. } else if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  1107. node = TraceDepend(node->cast<CNodePtr>());
  1108. flag = true;
  1109. }
  1110. }
  1111. return GetHandler(node, index_stack, draw_index);
  1112. }
  1113. void DfGraphConvertor::ConvertTupleGetItem(const CNodePtr node) {
  1114. auto handle = TraceRealOp(node);
  1115. if (handle.op == nullptr) {
  1116. MS_LOG(ERROR) << "Failed to trace tuple get item";
  1117. return;
  1118. }
  1119. out_handle_cache_[node.get()] = handle;
  1120. }
  1121. // Get the real op for tuple_getitem through make tuple, or depend
  1122. AnfNodePtr DfGraphConvertor::GetRealOpNode(AnfNodePtr node) {
  1123. const int TUPLE_GET_ITEM_INDEX = 2;
  1124. if (IsPrimitiveCNode(node, prim::kPrimTupleGetItem)) {
  1125. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1126. if (node_inputs.size() != 3) { // "tuple_getitem" primitive must have 3 inputs
  1127. MS_LOG(ERROR) << "tuple get item node not correct!";
  1128. error_ = FAILED;
  1129. return node;
  1130. }
  1131. MS_EXCEPTION_IF_NULL(node_inputs[TUPLE_GET_ITEM_INDEX]);
  1132. if (!node_inputs[TUPLE_GET_ITEM_INDEX]->isa<ValueNode>()) {
  1133. error_ = INVALID_ARGUMENT;
  1134. MS_LOG(EXCEPTION) << "can't convert get item with non-constant index";
  1135. }
  1136. auto value_ptr = GetValueNode(node_inputs[TUPLE_GET_ITEM_INDEX])->cast<Int32ImmPtr>();
  1137. if (value_ptr == nullptr) {
  1138. MS_LOG(ERROR) << "Can not convert get item as value is nullptr!";
  1139. error_ = FAILED;
  1140. return node;
  1141. }
  1142. int index = value_ptr->value();
  1143. // make_tuple apply inputs:make_tuple, [tuple_items,]
  1144. if (IsPrimitiveCNode(node_inputs[1], prim::kPrimMakeTuple)) {
  1145. auto tuple_inputs = node->cast<CNodePtr>()->inputs();
  1146. if (tuple_inputs.size() < IntToSize(index + 1)) {
  1147. MS_LOG(ERROR) << "make tuple input items node not correct! size:" << tuple_inputs.size()
  1148. << ", item index:" << index;
  1149. error_ = FAILED;
  1150. return node;
  1151. }
  1152. return GetRealOpNode(tuple_inputs[IntToSize(index + 1)]);
  1153. }
  1154. return GetRealOpNode(node_inputs[1]);
  1155. }
  1156. // depend apply inputs: depend,output,depended_node
  1157. if (IsPrimitiveCNode(node, prim::kPrimDepend)) {
  1158. auto depend_inputs = node->cast<CNodePtr>()->inputs();
  1159. if (depend_inputs.size() != 3) { // "Depend" primitive have 3 inputs
  1160. MS_LOG(ERROR) << "depend input items not correct";
  1161. error_ = FAILED;
  1162. return node;
  1163. }
  1164. return GetRealOpNode(depend_inputs[1]);
  1165. }
  1166. return node;
  1167. }
  1168. // convert the anf node to corresponding operator list
  1169. std::vector<OperatorPtr> DfGraphConvertor::ConvertDependNode(const AnfNodePtr node) {
  1170. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1171. std::vector<OperatorPtr> op_lists;
  1172. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1173. for (size_t index = 1; index < node_inputs.size(); index++) {
  1174. auto op = Convert(GetRealOpNode(node_inputs[index]));
  1175. if (op == nullptr) {
  1176. MS_LOG(ERROR) << "Convert control depend node to operator failed";
  1177. error_ = FAILED;
  1178. return std::vector<OperatorPtr>({});
  1179. }
  1180. op_lists.push_back(op);
  1181. }
  1182. return op_lists;
  1183. }
  1184. auto op = Convert(GetRealOpNode(node));
  1185. if (op == nullptr) {
  1186. MS_LOG(ERROR) << "Convert control depend node to operator failed";
  1187. error_ = FAILED;
  1188. return std::vector<OperatorPtr>({});
  1189. }
  1190. return std::vector<OperatorPtr>({op});
  1191. }
  1192. // get the anf node list for depend
  1193. std::vector<AnfNodePtr> DfGraphConvertor::GetDependNodes(const AnfNodePtr &node) {
  1194. std::vector<AnfNodePtr> nodes;
  1195. // for make tuple, should control depend on the tuple items
  1196. if (IsPrimitiveCNode(node, prim::kPrimMakeTuple)) {
  1197. auto node_inputs = node->cast<CNodePtr>()->inputs();
  1198. for (size_t index = 1; index < node_inputs.size(); index++) {
  1199. nodes.push_back(GetRealOpNode(node_inputs[index]));
  1200. }
  1201. return nodes;
  1202. }
  1203. // for parameter ,find the apply that used the parameter as the control depended node
  1204. if (node->isa<Parameter>()) {
  1205. auto uses = node->func_graph()->manager()->node_users()[node];
  1206. for (auto &use : uses) {
  1207. auto use_node = use.first;
  1208. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend))) {
  1209. nodes.push_back(GetRealOpNode(use_node));
  1210. }
  1211. }
  1212. return nodes;
  1213. }
  1214. nodes.push_back(GetRealOpNode(node));
  1215. return nodes;
  1216. }
  1217. void DfGraphConvertor::DrawControlDepend(const AnfNodePtr &src_node, const AnfNodePtr &dest_node) {
  1218. #ifdef DRAW_GE_GRAPH
  1219. auto src_depend_nodes = GetDependNodes(src_node);
  1220. auto dst_depend_nodes = GetDependNodes(dest_node);
  1221. if (src_depend_nodes.size() == 1 && dst_depend_nodes.size() > 1) {
  1222. for (auto &item : dst_depend_nodes) {
  1223. compute_sout_ << op_draw_name_[src_depend_nodes[0].get()] << " -> " << op_draw_name_[item.get()]
  1224. << "[style=\"dotted\"]" << endl;
  1225. }
  1226. } else if (src_depend_nodes.size() > 1 && dst_depend_nodes.size() == 1) {
  1227. for (auto &item : src_depend_nodes) {
  1228. compute_sout_ << op_draw_name_[item.get()] << " -> " << op_draw_name_[dst_depend_nodes[0].get()]
  1229. << "[style=\"dotted\"]" << endl;
  1230. }
  1231. } else if (src_depend_nodes.size() == 1 && dst_depend_nodes.size() == 1) {
  1232. compute_sout_ << op_draw_name_[src_depend_nodes[0].get()] << " -> " << op_draw_name_[dst_depend_nodes[0].get()]
  1233. << "[style=\"dotted\"]" << endl;
  1234. }
  1235. #endif
  1236. }
  1237. void DfGraphConvertor::GetDependOnParameterUse(const CNodePtr &node, const AnfNodePtr &src_node,
  1238. const AnfNodePtr &dest_node,
  1239. const std::shared_ptr<std::vector<OperatorPtr>> &src_ops_list,
  1240. const std::shared_ptr<std::vector<OperatorPtr>> &dst_ops_list) {
  1241. if (src_node->isa<Parameter>()) {
  1242. auto uses = node->func_graph()->manager()->node_users()[src_node];
  1243. for (auto &use : uses) {
  1244. auto use_node = use.first;
  1245. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend)) &&
  1246. (!IsPrimitiveCNode(use_node, prim::kPrimMakeTuple))) {
  1247. auto converted_list = ConvertDependNode(use_node);
  1248. src_ops_list->insert(src_ops_list->end(), converted_list.begin(), converted_list.end());
  1249. }
  1250. }
  1251. }
  1252. if (dest_node->isa<Parameter>()) {
  1253. auto uses = node->func_graph()->manager()->node_users()[dest_node];
  1254. for (auto &use : uses) {
  1255. auto use_node = use.first;
  1256. if ((use_node->isa<CNode>()) && (!IsPrimitiveCNode(use_node, prim::kPrimControlDepend)) &&
  1257. (!IsPrimitiveCNode(use_node, prim::kPrimMakeTuple))) {
  1258. auto converted_list = ConvertDependNode(use_node);
  1259. dst_ops_list->insert(dst_ops_list->end(), converted_list.begin(), converted_list.end());
  1260. }
  1261. }
  1262. }
  1263. }
  1264. bool DfGraphConvertor::GetControlDependList(const CNodePtr &node,
  1265. const std::shared_ptr<std::vector<OperatorPtr>> &src_ops_list,
  1266. const std::shared_ptr<std::vector<OperatorPtr>> &dst_ops_list) {
  1267. const int CONTROL_DEPEND_INDEX = 0;
  1268. const int SRC_NODE_INDEX = 1;
  1269. const int DEST_NODE_INDEX = 2;
  1270. const int DEPEND_MODE_NORMAL_USE = 0;
  1271. const int DEPEND_MODE_ON_PARAMETER_USE = 1;
  1272. auto node_inputs = node->inputs();
  1273. if (node_inputs.size() <= DEST_NODE_INDEX) {
  1274. MS_LOG(WARNING) << "Control depend node input size error";
  1275. return false;
  1276. }
  1277. auto src_node = node_inputs[SRC_NODE_INDEX];
  1278. auto dest_node = node_inputs[DEST_NODE_INDEX];
  1279. if ((src_node == nullptr) || (dest_node == nullptr)) {
  1280. MS_LOG(ERROR) << "Control depend node miss src or dest node";
  1281. error_ = FAILED;
  1282. return false;
  1283. }
  1284. AnfNodePtr fn = node_inputs[CONTROL_DEPEND_INDEX];
  1285. PrimitivePtr prim_ptr = GetValueNode<PrimitivePtr>(fn);
  1286. ValuePtr mode_ptr = prim_ptr->GetAttr("depend_mode");
  1287. int depend_mode = DEPEND_MODE_NORMAL_USE;
  1288. if (mode_ptr != nullptr) {
  1289. auto mode_int = mode_ptr->cast<Int32ImmPtr>();
  1290. MS_EXCEPTION_IF_NULL(mode_int);
  1291. depend_mode = mode_int->value();
  1292. MS_LOG(DEBUG) << "depend_mode = " << depend_mode;
  1293. }
  1294. if (depend_mode == DEPEND_MODE_ON_PARAMETER_USE) {
  1295. GetDependOnParameterUse(node, src_node, dest_node, src_ops_list, dst_ops_list);
  1296. }
  1297. if (src_node->isa<CNode>()) {
  1298. auto converted_list = ConvertDependNode(src_node);
  1299. src_ops_list->insert(src_ops_list->end(), converted_list.begin(), converted_list.end());
  1300. }
  1301. if (dest_node->isa<CNode>()) {
  1302. auto converted_list = ConvertDependNode(dest_node);
  1303. dst_ops_list->insert(dst_ops_list->end(), converted_list.begin(), converted_list.end());
  1304. }
  1305. if (src_ops_list->empty() || dst_ops_list->empty()) {
  1306. MS_LOG(DEBUG) << "Control depend node's src or dest node is not a CNode, ignore it";
  1307. error_ = SUCCESS;
  1308. }
  1309. return true;
  1310. }
  1311. void DfGraphConvertor::ConvertControlDependNode(const CNodePtr node) {
  1312. const int SRC_NODE_INDEX = 1;
  1313. const int DEST_NODE_INDEX = 2;
  1314. if (control_depend_cache_.find(node.get()) != control_depend_cache_.end()) {
  1315. return;
  1316. }
  1317. auto node_inputs = node->inputs();
  1318. if (node_inputs.size() <= DEST_NODE_INDEX) {
  1319. MS_LOG(WARNING) << "Control depend node input size error";
  1320. return;
  1321. }
  1322. auto src_node = node_inputs[SRC_NODE_INDEX];
  1323. auto dest_node = node_inputs[DEST_NODE_INDEX];
  1324. if ((src_node == nullptr) || (dest_node == nullptr)) {
  1325. MS_LOG(ERROR) << "Control depend node miss src or dest node";
  1326. error_ = FAILED;
  1327. return;
  1328. }
  1329. std::shared_ptr<std::vector<OperatorPtr>> src_ops_list = std::make_shared<std::vector<OperatorPtr>>();
  1330. std::shared_ptr<std::vector<OperatorPtr>> dst_ops_list = std::make_shared<std::vector<OperatorPtr>>();
  1331. if (!GetControlDependList(node, src_ops_list, dst_ops_list)) {
  1332. MS_LOG(ERROR) << "Get depend list failed";
  1333. error_ = FAILED;
  1334. return;
  1335. }
  1336. std::vector<ControlEdge> control_edges;
  1337. if (src_ops_list->size() == 1 && dst_ops_list->size() > 1) {
  1338. (void)std::transform(dst_ops_list->begin(), dst_ops_list->end(), std::back_inserter(control_edges),
  1339. [src_ops_list](const OperatorPtr &op) -> ControlEdge {
  1340. return {(*src_ops_list)[0], op};
  1341. });
  1342. } else if (src_ops_list->size() > 1 && dst_ops_list->size() == 1) {
  1343. (void)std::transform(src_ops_list->begin(), src_ops_list->end(), std::back_inserter(control_edges),
  1344. [dst_ops_list](const OperatorPtr &op) -> ControlEdge {
  1345. return {op, (*dst_ops_list)[0]};
  1346. });
  1347. } else if (src_ops_list->size() == 1 && dst_ops_list->size() == 1) {
  1348. control_edges.push_back({(*src_ops_list)[0], (*dst_ops_list)[0]});
  1349. } else if (src_ops_list->empty() || dst_ops_list->empty()) {
  1350. MS_LOG(DEBUG) << "Depend list of src or dst is empty, ignore it";
  1351. } else {
  1352. MS_LOG(ERROR) << "Convert control depend node to operator failed, depend src:" << src_ops_list->size()
  1353. << " -> dst:" << dst_ops_list->size();
  1354. error_ = FAILED;
  1355. return;
  1356. }
  1357. control_depend_cache_[node.get()] = control_edges;
  1358. #ifdef DRAW_GE_GRAPH
  1359. DrawControlDepend(src_node, dest_node);
  1360. #endif
  1361. }
  1362. bool DfGraphConvertor::CheckCNode(const std::string &name, const CNodePtr node) {
  1363. // ignore apply node of return
  1364. if (name == "return" || name == "Depend") {
  1365. return false;
  1366. }
  1367. if (name == "" && GetCNodeFuncName(node) == "switch_layer") {
  1368. return false;
  1369. }
  1370. if (name == "Partial") {
  1371. return false;
  1372. }
  1373. // make_tuple is used for a dynamic_input, convert it to a vector of OutHandlers
  1374. if (name == "make_tuple") {
  1375. ConvertMakeTuple(node);
  1376. return false;
  1377. }
  1378. // As for nodes with multi outputs, convert tuple_getitem to OutHandle
  1379. if (name == "tuple_getitem") {
  1380. ConvertTupleGetItem(node);
  1381. return false;
  1382. }
  1383. if (name == "ControlDepend") {
  1384. ConvertControlDependNode(node);
  1385. return false;
  1386. }
  1387. return true;
  1388. }
  1389. OperatorPtr DfGraphConvertor::ConvertCNode(const CNodePtr node) {
  1390. std::string name = GetCNodeTargetFuncName(node);
  1391. if (!CheckCNode(name, node)) {
  1392. return nullptr;
  1393. }
  1394. // get corresponding OpAdapter
  1395. OpAdapterPtr adpt = FindAdapter(node, training_);
  1396. if (adpt == nullptr) {
  1397. error_ = NOT_FOUND;
  1398. return nullptr;
  1399. }
  1400. // get operator
  1401. OperatorPtr op = nullptr;
  1402. auto it_op = op_cache_.find(node.get());
  1403. if (it_op != op_cache_.end()) {
  1404. op = it_op->second;
  1405. } else {
  1406. op = adpt->generate(node);
  1407. }
  1408. // set attribute for primitive
  1409. (void)adpt->setAttr(op, node);
  1410. // add into cache
  1411. (void)op_cache_.insert(std::make_pair(node.get(), op));
  1412. DrawCNode(node, adpt);
  1413. return op_cache_[node.get()];
  1414. }
  1415. OperatorPtr DfGraphConvertor::ConvertParameter(const AnfNodePtr node) {
  1416. // convert Parameter in ANF to variable in DataFlow
  1417. auto op = FindAdapter(node, training_)->generate(node);
  1418. op_cache_[node.get()] = op;
  1419. // build index for parameter using name
  1420. std::string name = std::static_pointer_cast<Parameter>(node)->name();
  1421. params_[name] = node;
  1422. std::ostringstream ss;
  1423. ss << "op" << node.get();
  1424. op_draw_name_[node.get()] = ss.str();
  1425. compute_sout_ << ss.str() << "[shape=octagon, label=\"" << name << "\"]" << endl;
  1426. return op_cache_[node.get()];
  1427. }
  1428. Status DfGraphConvertor::TryConvertValueNodeToMultiConst(const ValueNodePtr node) {
  1429. MS_EXCEPTION_IF_NULL(node);
  1430. ValuePtr value = node->value();
  1431. MS_EXCEPTION_IF_NULL(value);
  1432. if (!value->isa<ValueList>() && !value->isa<ValueTuple>()) {
  1433. return FAILED;
  1434. }
  1435. auto vec = value->isa<ValueTuple>() ? value->cast<ValueTuplePtr>()->value() : value->cast<ValueListPtr>()->value();
  1436. if (vec.empty()) {
  1437. return FAILED;
  1438. }
  1439. std::shared_ptr<std::vector<OutHandler>> tuple_items = std::make_shared<std::vector<OutHandler>>();
  1440. for (size_t i = 0; i < vec.size(); i++) {
  1441. MS_EXCEPTION_IF_NULL(vec[i]);
  1442. if (vec[i]->isa<MeTensor>()) {
  1443. GeTensorPtr ge_tensor = transform::TransformUtil::ConvertTensor(vec[i]->cast<MeTensorPtr>(), kOpFormat_NCHW);
  1444. auto const_op = std::make_shared<Constant>(node->fullname_with_scope() + "/const/inputs/" + std::to_string(i));
  1445. (void)const_op->set_attr_value(*ge_tensor);
  1446. (void)const_op->update_output_desc_y(ge_tensor->GetTensorDesc());
  1447. tuple_items->emplace_back(OutHandler(const_op, ""));
  1448. } else {
  1449. return FAILED;
  1450. }
  1451. }
  1452. if (tuple_items->empty()) {
  1453. return FAILED;
  1454. }
  1455. tuple_out_handle_cache_[node.get()] = tuple_items;
  1456. return SUCCESS;
  1457. }
  1458. OperatorPtr DfGraphConvertor::ConvertValueNode(const ValueNodePtr node) {
  1459. // convert valuenode in ANF to Const in DataFlow
  1460. // find paramerte referenced by SymbolicKeyInstance of valuenode
  1461. std::ostringstream ss;
  1462. ss << "op" << node.get();
  1463. op_draw_name_[node.get()] = ss.str();
  1464. compute_sout_ << ss.str() << "[label= \"" << node->value()->ToString() << "\" shape=ellipse]" << endl;
  1465. if (TryConvertValueNodeToMultiConst(node) == SUCCESS) {
  1466. MS_LOG(INFO) << "Convert value node to multi Constant OP success";
  1467. return nullptr;
  1468. }
  1469. OpAdapterPtr adpt = FindAdapter(node, training_);
  1470. if (adpt == nullptr) {
  1471. error_ = NOT_FOUND;
  1472. return nullptr;
  1473. }
  1474. auto op = adpt->generate(node);
  1475. // set const's attrs
  1476. if (adpt->setAttr(op, "value", node->value()) != 0) {
  1477. MS_LOG(WARNING) << "set attr value for const failed";
  1478. }
  1479. #if (defined ENABLE_GE)
  1480. auto const_op = std::static_pointer_cast<Constant>(op);
  1481. if (const_op == nullptr) {
  1482. MS_LOG(ERROR) << "Get Constant operator failed";
  1483. return nullptr;
  1484. }
  1485. auto ge_tensor = const_op->get_attr_value();
  1486. auto ge_desc = ge_tensor.GetTensorDesc();
  1487. (void)const_op->update_output_desc_y(ge_desc);
  1488. #endif
  1489. op_cache_[node.get()] = op;
  1490. return op_cache_[node.get()];
  1491. }
  1492. void DfGraphConvertor::DrawCNode(const CNodePtr node, const OpAdapterPtr adpt) {
  1493. if (nullptr == adpt || nullptr == node) {
  1494. MS_LOG(ERROR) << "Failed to draw apply node as adpt or node is nullptr!";
  1495. return;
  1496. }
  1497. std::ostringstream ss;
  1498. ss << "op" << node.get();
  1499. op_draw_name_[node.get()] = ss.str();
  1500. compute_sout_ << ss.str() << "[label=<";
  1501. compute_sout_ << "<table border='1' cellborder='1'>" << endl;
  1502. auto input_map = adpt->getInputMap();
  1503. auto dyn_input_map = adpt->getDynInputMap();
  1504. if (input_map.size() + dyn_input_map.size() > 0) {
  1505. compute_sout_ << "<tr>";
  1506. for (auto &it : input_map) {
  1507. compute_sout_ << "<td port='" << it.first << "'>" << it.second.name << "</td>";
  1508. }
  1509. for (auto &it : dyn_input_map) {
  1510. compute_sout_ << "<td port='" << it.first << "'>" << it.second.name << "</td>";
  1511. }
  1512. compute_sout_ << "</tr>" << endl;
  1513. }
  1514. compute_sout_ << "<tr><td colspan=\"" << (input_map.size() + dyn_input_map.size()) << "\">\"" << node->ToString()
  1515. << ":" << GetCNodeTargetFuncName(node) << "\"</td></tr>" << endl;
  1516. // print attrs' values
  1517. auto atts = adpt->GetAttrsFromDrawGraph();
  1518. for (auto &it : atts) {
  1519. compute_sout_ << "<tr><td colspan=\"" << (input_map.size() + dyn_input_map.size()) << "\">\"" << it
  1520. << "\"</td></tr>";
  1521. }
  1522. adpt->clearAttrVect();
  1523. compute_sout_ << "</table>> shape=plaintext]" << endl;
  1524. }
  1525. void DfGraphConvertor::RegisterAdapter(const std::string &name, OpAdapterPtr adpt) {
  1526. OpAdapterMap::get()[name] = std::make_shared<OpAdapterDesc>(adpt);
  1527. }
  1528. void DfGraphConvertor::RegisterAdapter(const std::string &name, OpAdapterPtr train_adpt, OpAdapterPtr infer_adpt) {
  1529. OpAdapterMap::get()[name] = std::make_shared<OpAdapterDesc>(train_adpt, infer_adpt);
  1530. }
  1531. } // namespace transform
  1532. } // namespace mindspore